Skip to main content

af_price_updates/
pyth.rs

1//! Pyth accumulator (`PNAU`) price update format and feed identifiers.
2
3pub use crate::pyth_id_set::PriceFeedIdSet;
4use crate::reader::{Reader, decode_base64};
5use crate::{ParseError, U256, sorted_set::SortedSetSlice};
6use bytes::{Bytes, BytesMut};
7use serde::{Deserialize, Serialize};
8use std::io::{Error, ErrorKind};
9
10/// Pyth price feed ID, displayed and parsed as `0x`-prefixed hex.
11#[derive(
12    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
13)]
14#[repr(transparent)]
15pub struct PriceFeedId(pub U256);
16
17/// A parsed Pyth feed.
18#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
19pub struct Feed {
20    /// ID of the feed.
21    pub feed_id: PriceFeedId,
22    /// The price.
23    pub price: Price,
24    /// Exponential moving average of the price.
25    pub ema_price: Price,
26}
27
28/// A Pyth price with its confidence interval.
29#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize)]
30pub struct Price {
31    /// Price mantissa; the price is `price * 10^exponent`.
32    pub price: i64,
33    /// Confidence interval around the price, with the same exponent.
34    pub confidence: u64,
35    /// Decimal exponent of `price` and `confidence`.
36    pub exponent: i32,
37    /// Publish time in seconds since the Unix epoch.
38    pub timestamp: u64,
39}
40
41impl std::fmt::Display for PriceFeedId {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
43        <U256 as std::fmt::Display>::fmt(&self.0, f)
44    }
45}
46
47impl std::str::FromStr for PriceFeedId {
48    type Err = ParseError;
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        s.parse::<U256>().map(PriceFeedId)
51    }
52}
53
54impl From<[u8; 32]> for PriceFeedId {
55    fn from(bytes: [u8; 32]) -> Self {
56        Self(U256::from(bytes))
57    }
58}
59
60impl AsRef<[u8]> for PriceFeedId {
61    fn as_ref(&self) -> &[u8] {
62        self.0.as_ref()
63    }
64}
65
66const MAGIC: u32 = u32::from_be_bytes(*b"PNAU");
67const MAJOR_VERSION: u8 = 1;
68const PROOF_TYPE: u8 = 0;
69const MESSAGE_LEN: u16 = 85;
70const MESSAGE_TYPE: u8 = 0;
71
72/// A Pyth accumulator (`PNAU`) update with exactly one feed.
73///
74/// Constructors check the layout only and never verify the VAA or Merkle proofs, which is left to
75/// the on-chain Pyth contract.
76#[derive(Clone, Debug, Eq, Hash, PartialEq)]
77pub struct PriceUpdate(Bytes);
78
79impl TryFrom<BytesMut> for PriceUpdate {
80    type Error = Error;
81    /// Copies the bytes, like [`PriceUpdate::from_slice`], so the update does not keep a larger
82    /// buffer that `bytes` may share alive.
83    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
84        Self::from_slice(&bytes)
85    }
86}
87
88impl PriceUpdate {
89    /// Checks and copies an update with exactly one feed.
90    pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
91        check_bytes_with_one_feed(bytes)?;
92        Ok(Self(Bytes::copy_from_slice(bytes)))
93    }
94    /// Checks an update with exactly one feed and keeps `bytes` without copying.
95    ///
96    /// Use [`Self::from_slice`] instead to copy the update out of a larger buffer.
97    pub fn from_bytes(bytes: Bytes) -> Result<Self, Error> {
98        check_bytes_with_one_feed(&bytes)?;
99        Ok(Self(bytes))
100    }
101    /// Decodes a standard, padded base64 update and checks it has exactly one feed.
102    ///
103    /// Decodes in place when `base64` is the only owner of its buffer, such as a `String`, a
104    /// `Vec<u8>` or the bytes of an unshared `bytestring::ByteString`, and copies it otherwise.
105    pub fn from_base64(base64: impl Into<Bytes>) -> Result<Self, Error> {
106        Self::from_bytes(decode_base64(base64.into(), "Pyth")?)
107    }
108    /// The whole update.
109    pub fn as_bytes(&self) -> &[u8] {
110        &self.0
111    }
112    /// The whole update, to share without copying.
113    pub const fn bytes(&self) -> &Bytes {
114        &self.0
115    }
116    /// The whole update, without copying.
117    pub fn into_bytes(self) -> Bytes {
118        self.0
119    }
120    /// The Wormhole VAA of the update.
121    pub fn vaa(&self) -> &[u8] {
122        vaa(&self.0)
123    }
124    /// The feed of the update.
125    pub fn feed(&self) -> Feed {
126        feeds(&self.0).next().expect("checked on construction")
127    }
128}
129
130/// A Pyth accumulator (`PNAU`) update with any number of feeds.
131///
132/// Constructors check the layout only and never verify the VAA or Merkle proofs, which is left to
133/// the on-chain Pyth contract.
134#[derive(Clone, Debug, Eq, Hash, PartialEq)]
135pub struct PriceUpdates(Bytes);
136
137impl TryFrom<BytesMut> for PriceUpdates {
138    type Error = Error;
139    /// Copies the bytes, like [`PriceUpdates::from_slice`], so the update does not keep a larger
140    /// buffer that `bytes` may share alive.
141    fn try_from(bytes: BytesMut) -> Result<Self, Self::Error> {
142        Self::from_slice(&bytes)
143    }
144}
145
146impl PriceUpdates {
147    /// Checks and copies an update.
148    pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
149        check_bytes(bytes)?;
150        Ok(Self(Bytes::copy_from_slice(bytes)))
151    }
152    /// Checks an update and keeps `bytes` without copying.
153    ///
154    /// Use [`Self::from_slice`] instead to copy the update out of a larger buffer.
155    pub fn from_bytes(bytes: Bytes) -> Result<Self, Error> {
156        check_bytes(&bytes)?;
157        Ok(Self(bytes))
158    }
159    /// Decodes a standard, padded base64 update and checks it.
160    ///
161    /// Decodes in place when `base64` is the only owner of its buffer, such as a `String`, a
162    /// `Vec<u8>` or the bytes of an unshared `bytestring::ByteString`, and copies it otherwise.
163    pub fn from_base64(base64: impl Into<Bytes>) -> Result<Self, Error> {
164        Self::from_bytes(decode_base64(base64.into(), "Pyth")?)
165    }
166    /// The whole update.
167    pub fn as_bytes(&self) -> &[u8] {
168        &self.0
169    }
170    /// The whole update, to share without copying.
171    pub const fn bytes(&self) -> &Bytes {
172        &self.0
173    }
174    /// The whole update, without copying.
175    pub fn into_bytes(self) -> Bytes {
176        self.0
177    }
178    /// The Wormhole VAA of the update.
179    pub fn vaa(&self) -> &[u8] {
180        vaa(&self.0)
181    }
182    /// Number of feeds in the update.
183    pub fn feed_count(&self) -> usize {
184        self.feeds().len()
185    }
186    /// Feeds of the update, in the order sent.
187    pub fn feeds(&self) -> impl Clone + ExactSizeIterator<Item = Feed> {
188        feeds(&self.0)
189    }
190    /// The first feed with `feed_id`, if any.
191    pub fn feed(&self, feed_id: PriceFeedId) -> Option<Feed> {
192        self.feeds().find(|feed| feed.feed_id == feed_id)
193    }
194    /// Returns whether the update contains every ID in `feed_ids` exactly once and no other IDs.
195    ///
196    /// Pass a reference to a [`PriceFeedIdSet`], [`SortedSet`](crate::sorted_set::SortedSet), or
197    /// [`ArcSortedSet`](crate::sorted_set::ArcSortedSet); deref coercion borrows its
198    /// [`SortedSetSlice`] view. Feed order does not matter. This check does not allocate: it uses
199    /// the sorted indices of `feed_ids` and a fixed-size stack bitmap to detect repeated IDs.
200    pub fn matches_set(&self, feed_ids: &SortedSetSlice<PriceFeedId>) -> bool {
201        feed_ids.exactly_matches_bounded_iter(self.feeds().map(|feed| feed.feed_id))
202    }
203}
204
205fn vaa(bytes: &[u8]) -> &[u8] {
206    let mut reader = Reader(bytes);
207    let header = take_header(&mut reader).expect("checked on construction");
208    reader
209        .take(header.vaa_len as usize)
210        .expect("checked on construction")
211}
212
213fn feeds(bytes: &[u8]) -> impl Clone + ExactSizeIterator<Item = Feed> {
214    let mut reader = Reader(bytes);
215    let header = take_header(&mut reader).expect("checked on construction");
216    reader
217        .skip(header.vaa_len as usize)
218        .expect("checked on construction");
219    let feed_count = take_feed_count(&mut reader).expect("checked on construction");
220    (0..feed_count)
221        .map(move |_| take_feed_with_proof(&mut reader).expect("checked on construction"))
222}
223
224/// Checks the structure of an update, not its VAA or Merkle proofs, and returns its feed count.
225fn check_bytes(bytes: &[u8]) -> Result<u8, Error> {
226    let mut reader = Reader(bytes);
227    let header = take_header(&mut reader)?;
228    header.check()?;
229    reader.skip(header.vaa_len as usize)?;
230    let feed_count = take_feed_count(&mut reader)?;
231    for _ in 0..feed_count {
232        let _feed = take_feed_with_proof(&mut reader)?;
233    }
234    reader.assert_eof()?;
235    Ok(feed_count)
236}
237
238fn check_bytes_with_one_feed(bytes: &[u8]) -> Result<(), Error> {
239    if check_bytes(bytes)? != 1 {
240        return Err(Error::new(
241            ErrorKind::InvalidData,
242            "Pyth update does not have exactly one feed",
243        ));
244    }
245    Ok(())
246}
247
248#[derive(Debug)]
249struct Header {
250    magic: u32,
251    major_version: u8,
252    _minor_version: u8,
253    _trailing_payload_len: u8,
254    proof_type: u8,
255    vaa_len: u16,
256}
257
258impl Header {
259    fn check(&self) -> Result<(), Error> {
260        if self.magic != MAGIC {
261            return Err(Error::new(
262                ErrorKind::InvalidData,
263                "Pyth invalid magic number",
264            ));
265        }
266        if self.major_version != MAJOR_VERSION {
267            return Err(Error::new(ErrorKind::InvalidData, "Pyth invalid version"));
268        }
269        if self.proof_type != PROOF_TYPE {
270            return Err(Error::new(
271                ErrorKind::InvalidData,
272                "Pyth invalid proof type",
273            ));
274        }
275        Ok(())
276    }
277}
278
279fn take_header(reader: &mut Reader<'_>) -> Result<Header, Error> {
280    let magic = u32::from_be_bytes(reader.take_chunk()?);
281    let major_version = u8::from_be_bytes(reader.take_chunk()?);
282    let minor_version = u8::from_be_bytes(reader.take_chunk()?);
283    let trailing_payload_len = u8::from_be_bytes(reader.take_chunk()?);
284    reader.skip(trailing_payload_len as usize)?;
285    let proof_type = u8::from_be_bytes(reader.take_chunk()?);
286    let vaa_length = u16::from_be_bytes(reader.take_chunk()?);
287    Ok(Header {
288        magic,
289        major_version,
290        _minor_version: minor_version,
291        _trailing_payload_len: trailing_payload_len,
292        proof_type,
293        vaa_len: vaa_length,
294    })
295}
296
297fn take_feed_count(reader: &mut Reader<'_>) -> Result<u8, Error> {
298    Ok(u8::from_be_bytes(reader.take_chunk()?))
299}
300
301fn take_feed_with_proof(reader: &mut Reader<'_>) -> Result<Feed, Error> {
302    let feed = take_feed(reader)?;
303    let proof_len = 20usize * take_feed_count(reader)? as usize;
304    reader.skip(proof_len)?;
305    Ok(feed)
306}
307
308fn take_feed(reader: &mut Reader<'_>) -> Result<Feed, Error> {
309    let message_len = u16::from_be_bytes(reader.take_chunk()?);
310    if message_len != MESSAGE_LEN {
311        return Err(Error::new(
312            ErrorKind::InvalidData,
313            "Pyth invalid message length",
314        ));
315    }
316    let message_type = u8::from_be_bytes(reader.take_chunk()?);
317    if message_type != MESSAGE_TYPE {
318        return Err(Error::new(
319            ErrorKind::InvalidData,
320            "Pyth invalid message type",
321        ));
322    }
323    let feed_id = PriceFeedId(U256::from(reader.take_chunk()?));
324    let price = i64::from_be_bytes(reader.take_chunk()?);
325    let confidence = u64::from_be_bytes(reader.take_chunk()?);
326    let exponent = i32::from_be_bytes(reader.take_chunk()?);
327    let timestamp = u64::from_be_bytes(reader.take_chunk()?);
328    let _prev_timestamp = i64::from_be_bytes(reader.take_chunk()?);
329    let ema_price = i64::from_be_bytes(reader.take_chunk()?);
330    let ema_confidence = u64::from_be_bytes(reader.take_chunk()?);
331    Ok(Feed {
332        feed_id,
333        price: Price {
334            price,
335            confidence,
336            exponent,
337            timestamp,
338        },
339        ema_price: Price {
340            price: ema_price,
341            confidence: ema_confidence,
342            exponent,
343            timestamp,
344        },
345    })
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use base64ct::{Base64, Encoding as _};
352
353    fn test_feed(id: u8, price: i64) -> Feed {
354        Feed {
355            feed_id: PriceFeedId(U256::from(u64::from(id))),
356            price: Price {
357                price,
358                confidence: 100,
359                exponent: -8,
360                timestamp: 1_700_000_000,
361            },
362            ema_price: Price {
363                price,
364                confidence: 200,
365                exponent: -8,
366                timestamp: 1_700_000_000,
367            },
368        }
369    }
370
371    fn push_feed(bytes: &mut Vec<u8>, feed: Feed) {
372        bytes.extend_from_slice(&MESSAGE_LEN.to_be_bytes());
373        bytes.push(MESSAGE_TYPE);
374        bytes.extend_from_slice(feed.feed_id.0.as_slice());
375        bytes.extend_from_slice(&feed.price.price.to_be_bytes());
376        bytes.extend_from_slice(&feed.price.confidence.to_be_bytes());
377        bytes.extend_from_slice(&feed.price.exponent.to_be_bytes());
378        bytes.extend_from_slice(&feed.price.timestamp.to_be_bytes());
379        bytes.extend_from_slice(&0i64.to_be_bytes());
380        bytes.extend_from_slice(&feed.ema_price.price.to_be_bytes());
381        bytes.extend_from_slice(&feed.ema_price.confidence.to_be_bytes());
382        bytes.push(0);
383    }
384
385    fn price_updates_bytes(feeds: &[Feed]) -> Bytes {
386        let mut bytes = Vec::new();
387        bytes.extend_from_slice(&MAGIC.to_be_bytes());
388        bytes.push(MAJOR_VERSION);
389        bytes.push(0);
390        bytes.push(0);
391        bytes.push(PROOF_TYPE);
392        bytes.extend_from_slice(&0u16.to_be_bytes());
393        bytes.push(feeds.len().try_into().unwrap());
394        for feed in feeds {
395            push_feed(&mut bytes, *feed);
396        }
397        bytes.into()
398    }
399
400    #[test]
401    fn feed_serde_uses_public_field_names() {
402        let feed = test_feed(1, 42);
403        let json = serde_json::to_value(feed).unwrap();
404
405        assert!(json.get("feed_id").is_some());
406        assert_eq!(json["price"]["confidence"], 100);
407        assert_eq!(json["price"]["exponent"], -8);
408        assert_eq!(serde_json::from_value::<Feed>(json).unwrap(), feed);
409    }
410
411    #[test]
412    fn price_update_accepts_single_feed_payload() {
413        let feed = test_feed(1, 42);
414        let update = PriceUpdate::from_bytes(price_updates_bytes(&[feed])).unwrap();
415
416        assert_eq!(update.feed(), feed);
417    }
418
419    #[test]
420    fn price_update_rejects_multi_feed_payload() {
421        let bytes = price_updates_bytes(&[test_feed(1, 42), test_feed(2, 43)]);
422
423        assert!(PriceUpdate::from_bytes(bytes).is_err());
424    }
425
426    #[test]
427    fn price_updates_iterates_multi_feed_payload() {
428        let feeds = [test_feed(1, 42), test_feed(2, 43)];
429        let updates = PriceUpdates::from_bytes(price_updates_bytes(&feeds)).unwrap();
430
431        assert_eq!(updates.feed_count(), 2);
432        assert_eq!(updates.feeds().collect::<Vec<_>>(), feeds);
433        assert_eq!(updates.feed(feeds[1].feed_id), Some(feeds[1]));
434        assert_eq!(updates.feed(test_feed(3, 44).feed_id), None);
435    }
436
437    #[test]
438    fn price_feed_id_converts_from_and_to_bytes() {
439        let mut bytes = [0; 32];
440        bytes[31] = 7;
441        let id = PriceFeedId::from(bytes);
442
443        assert_eq!(id, PriceFeedId(U256::from(7)));
444        assert_eq!(id.as_ref(), bytes.as_slice());
445    }
446
447    #[test]
448    fn price_updates_matches_set_rejects_repeated_ids() {
449        let first = test_feed(1, 42);
450        let second = test_feed(2, 43);
451        let expected = PriceFeedIdSet::from([first.feed_id, second.feed_id]);
452
453        let reversed = PriceUpdates::from_bytes(price_updates_bytes(&[second, first])).unwrap();
454        assert!(reversed.matches_set(&expected));
455
456        let repeated = PriceUpdates::from_bytes(price_updates_bytes(&[first, first])).unwrap();
457        assert!(!repeated.matches_set(&expected));
458    }
459
460    #[test]
461    fn price_update_and_updates_construct_alike() {
462        let feeds = [test_feed(1, 42)];
463        let bytes = price_updates_bytes(&feeds);
464
465        let update = PriceUpdate::from_slice(&bytes).unwrap();
466        assert_eq!(update, PriceUpdate::from_bytes(bytes.clone()).unwrap());
467        assert_eq!(
468            update,
469            PriceUpdate::try_from(BytesMut::from(&bytes[..])).unwrap()
470        );
471        assert_eq!(update.bytes(), &bytes);
472
473        let updates = PriceUpdates::from_slice(&bytes).unwrap();
474        assert_eq!(updates, PriceUpdates::from_bytes(bytes.clone()).unwrap());
475        assert_eq!(
476            updates,
477            PriceUpdates::try_from(BytesMut::from(&bytes[..])).unwrap()
478        );
479        assert_eq!(updates.into_bytes(), bytes);
480    }
481
482    /// Hermes update of USDC/USD and USDT/USD with a 952-byte VAA and 12 proof hashes per feed.
483    const HERMES_PRICE_UPDATES: &[u8] = &[
484        80, 78, 65, 85, 1, 0, 0, 0, 3, 184, 1, 0, 0, 0, 4, 13, 2, 227, 24, 96, 99, 71, 25, 153,
485        168, 64, 62, 5, 239, 214, 91, 168, 20, 170, 63, 109, 144, 13, 7, 115, 70, 224, 77, 98, 81,
486        30, 84, 91, 39, 13, 232, 125, 67, 36, 53, 99, 202, 197, 133, 80, 74, 157, 12, 189, 220, 28,
487        151, 199, 188, 225, 109, 209, 249, 96, 183, 5, 42, 226, 192, 38, 138, 0, 3, 249, 120, 36,
488        58, 7, 92, 85, 172, 179, 237, 151, 245, 248, 82, 75, 158, 19, 63, 114, 199, 222, 9, 163,
489        231, 65, 141, 52, 212, 96, 238, 6, 49, 87, 79, 72, 233, 130, 88, 55, 156, 73, 61, 84, 147,
490        109, 16, 223, 189, 158, 197, 53, 244, 65, 187, 33, 120, 99, 149, 185, 191, 242, 92, 66,
491        191, 0, 4, 30, 240, 168, 168, 247, 51, 78, 48, 103, 240, 249, 4, 192, 211, 169, 152, 41,
492        145, 18, 28, 200, 5, 38, 124, 61, 24, 19, 172, 116, 80, 164, 66, 21, 133, 130, 184, 8, 98,
493        220, 30, 120, 114, 33, 149, 117, 191, 18, 181, 131, 235, 27, 36, 209, 115, 130, 163, 6, 23,
494        124, 236, 171, 124, 112, 44, 1, 6, 209, 141, 41, 100, 143, 78, 41, 21, 243, 59, 150, 177,
495        90, 178, 237, 29, 145, 149, 37, 46, 240, 3, 195, 241, 80, 245, 180, 84, 61, 14, 170, 237,
496        122, 201, 27, 198, 73, 186, 234, 154, 66, 207, 67, 75, 240, 174, 249, 142, 48, 228, 111, 4,
497        200, 190, 172, 246, 63, 254, 34, 163, 128, 122, 16, 210, 0, 8, 191, 220, 51, 253, 57, 50,
498        163, 79, 88, 232, 126, 172, 170, 89, 130, 65, 176, 182, 91, 240, 164, 35, 213, 132, 158,
499        97, 102, 50, 162, 96, 114, 139, 98, 157, 119, 102, 231, 146, 166, 8, 6, 18, 60, 177, 86,
500        233, 26, 235, 227, 155, 225, 197, 132, 61, 6, 118, 109, 248, 24, 140, 30, 52, 6, 43, 1, 10,
501        85, 29, 249, 163, 156, 13, 212, 77, 180, 47, 238, 93, 158, 18, 64, 40, 222, 167, 1, 33,
502        140, 168, 197, 159, 241, 17, 243, 0, 58, 92, 199, 31, 89, 162, 159, 123, 3, 64, 152, 23,
503        197, 125, 37, 84, 80, 165, 182, 200, 181, 78, 196, 118, 123, 1, 70, 177, 37, 116, 240, 202,
504        224, 220, 109, 158, 1, 11, 221, 209, 41, 251, 32, 55, 58, 61, 152, 110, 10, 62, 186, 60,
505        86, 65, 160, 71, 81, 1, 59, 126, 69, 71, 216, 204, 52, 229, 0, 185, 127, 57, 14, 206, 70,
506        155, 120, 85, 117, 170, 225, 235, 12, 190, 234, 184, 58, 164, 225, 5, 12, 223, 251, 0, 52,
507        59, 221, 225, 126, 233, 217, 92, 116, 213, 0, 12, 152, 157, 113, 192, 198, 238, 172, 110,
508        191, 190, 246, 149, 85, 188, 218, 83, 7, 104, 78, 189, 150, 0, 236, 198, 121, 181, 51, 177,
509        154, 109, 144, 89, 125, 120, 175, 40, 22, 245, 71, 29, 146, 119, 31, 193, 103, 5, 250, 72,
510        228, 130, 239, 17, 240, 130, 196, 167, 133, 169, 212, 235, 207, 43, 210, 171, 1, 13, 172,
511        96, 175, 189, 130, 166, 32, 89, 101, 136, 219, 122, 111, 245, 232, 150, 200, 191, 50, 211,
512        176, 232, 11, 87, 250, 222, 112, 160, 149, 249, 101, 52, 88, 103, 53, 13, 80, 101, 152, 75,
513        5, 191, 204, 201, 122, 107, 135, 35, 88, 199, 254, 233, 74, 253, 15, 116, 58, 170, 106,
514        100, 219, 174, 254, 183, 0, 14, 112, 221, 237, 236, 198, 85, 71, 134, 82, 99, 128, 145, 28,
515        187, 213, 66, 75, 75, 9, 124, 139, 242, 194, 156, 80, 157, 44, 46, 189, 214, 30, 32, 22,
516        219, 212, 50, 92, 236, 147, 183, 177, 185, 71, 140, 28, 189, 62, 96, 176, 208, 55, 230, 78,
517        248, 218, 35, 242, 234, 238, 14, 212, 97, 166, 75, 1, 15, 169, 162, 176, 251, 32, 122, 144,
518        165, 152, 196, 29, 22, 221, 250, 160, 216, 139, 215, 33, 58, 218, 234, 26, 248, 82, 215,
519        204, 15, 96, 79, 31, 182, 22, 97, 57, 75, 199, 107, 14, 2, 18, 146, 69, 92, 159, 99, 120,
520        191, 171, 3, 156, 101, 66, 131, 158, 82, 117, 42, 117, 67, 57, 141, 168, 28, 1, 16, 247, 2,
521        110, 59, 2, 102, 15, 43, 243, 29, 48, 44, 244, 115, 217, 192, 162, 199, 181, 250, 26, 227,
522        46, 145, 85, 190, 125, 226, 207, 225, 151, 247, 42, 140, 96, 25, 47, 210, 129, 51, 67, 133,
523        201, 98, 151, 19, 159, 167, 59, 177, 193, 240, 217, 142, 41, 26, 226, 2, 34, 62, 39, 94,
524        156, 232, 1, 17, 175, 70, 184, 165, 201, 132, 123, 10, 1, 152, 213, 221, 143, 15, 127, 102,
525        4, 200, 101, 172, 116, 105, 115, 239, 27, 66, 67, 7, 69, 215, 19, 158, 54, 227, 2, 53, 97,
526        243, 163, 250, 62, 100, 112, 39, 242, 95, 186, 138, 251, 250, 229, 5, 133, 6, 225, 249,
527        221, 150, 166, 18, 21, 71, 247, 142, 1, 104, 63, 14, 207, 0, 0, 0, 0, 0, 26, 225, 1, 250,
528        237, 172, 88, 81, 227, 43, 155, 35, 181, 249, 65, 26, 140, 43, 172, 74, 174, 62, 212, 221,
529        123, 129, 29, 209, 167, 46, 164, 170, 113, 0, 0, 0, 0, 8, 31, 235, 202, 1, 65, 85, 87, 86,
530        0, 0, 0, 0, 0, 13, 45, 109, 26, 0, 0, 39, 16, 10, 180, 224, 234, 57, 33, 123, 195, 241, 46,
531        211, 107, 68, 85, 235, 149, 196, 95, 190, 111, 2, 0, 85, 0, 234, 160, 32, 198, 28, 196,
532        121, 113, 40, 19, 70, 28, 225, 83, 137, 74, 150, 166, 192, 11, 33, 237, 12, 252, 39, 152,
533        209, 249, 169, 233, 201, 74, 0, 0, 0, 0, 5, 245, 137, 177, 0, 0, 0, 0, 0, 1, 173, 206, 255,
534        255, 255, 248, 0, 0, 0, 0, 104, 63, 14, 207, 0, 0, 0, 0, 104, 63, 14, 206, 0, 0, 0, 0, 5,
535        245, 135, 212, 0, 0, 0, 0, 0, 1, 163, 1, 12, 59, 102, 57, 97, 120, 243, 39, 75, 249, 134,
536        125, 242, 206, 38, 134, 17, 150, 44, 146, 76, 241, 107, 157, 216, 217, 170, 43, 18, 17,
537        227, 13, 103, 49, 173, 226, 195, 235, 215, 254, 89, 241, 120, 15, 3, 70, 9, 118, 41, 60,
538        125, 193, 189, 62, 158, 1, 21, 216, 218, 234, 190, 94, 186, 201, 201, 211, 111, 180, 93,
539        250, 13, 40, 61, 191, 149, 246, 78, 42, 86, 28, 112, 229, 220, 15, 66, 200, 80, 170, 108,
540        96, 175, 200, 103, 77, 39, 57, 241, 217, 167, 70, 198, 74, 7, 203, 19, 145, 241, 242, 61,
541        152, 213, 227, 81, 121, 83, 202, 207, 24, 215, 179, 29, 184, 162, 32, 199, 60, 119, 46,
542        246, 1, 134, 69, 66, 26, 126, 207, 182, 189, 208, 142, 189, 21, 28, 184, 186, 26, 235, 67,
543        250, 102, 225, 215, 63, 29, 56, 232, 247, 24, 1, 51, 116, 69, 38, 195, 244, 248, 180, 50,
544        43, 104, 58, 203, 159, 30, 53, 114, 207, 143, 42, 28, 167, 75, 204, 97, 2, 222, 80, 53,
545        178, 137, 26, 243, 203, 140, 83, 97, 75, 172, 245, 248, 76, 139, 58, 225, 142, 207, 32, 15,
546        69, 159, 149, 236, 65, 146, 92, 99, 233, 61, 66, 165, 230, 18, 50, 243, 5, 47, 247, 1, 145,
547        156, 73, 65, 244, 92, 190, 23, 37, 180, 126, 155, 198, 0, 85, 0, 43, 137, 185, 220, 143,
548        223, 159, 52, 112, 154, 91, 16, 107, 71, 47, 15, 57, 187, 108, 169, 206, 4, 176, 253, 127,
549        46, 151, 22, 136, 226, 229, 59, 0, 0, 0, 0, 5, 246, 228, 237, 0, 0, 0, 0, 0, 0, 245, 28,
550        255, 255, 255, 248, 0, 0, 0, 0, 104, 63, 14, 207, 0, 0, 0, 0, 104, 63, 14, 206, 0, 0, 0, 0,
551        5, 246, 198, 226, 0, 0, 0, 0, 0, 0, 238, 115, 12, 25, 196, 58, 108, 30, 84, 208, 12, 80,
552        67, 9, 137, 31, 95, 121, 104, 222, 40, 236, 228, 119, 232, 203, 135, 231, 159, 142, 125,
553        131, 59, 142, 30, 106, 236, 110, 62, 201, 199, 87, 89, 208, 80, 128, 78, 67, 108, 208, 27,
554        98, 210, 56, 122, 86, 140, 91, 35, 230, 10, 150, 225, 245, 69, 141, 19, 245, 33, 175, 204,
555        82, 113, 138, 28, 81, 255, 237, 128, 239, 38, 155, 12, 194, 83, 191, 149, 143, 4, 243, 4,
556        124, 172, 77, 176, 90, 41, 130, 63, 245, 165, 181, 217, 246, 165, 105, 205, 226, 193, 170,
557        150, 170, 44, 192, 62, 147, 214, 143, 243, 89, 182, 76, 73, 201, 35, 194, 60, 149, 118, 78,
558        143, 237, 202, 62, 38, 11, 131, 165, 23, 199, 225, 248, 38, 25, 9, 20, 63, 136, 146, 201,
559        252, 7, 210, 157, 124, 142, 174, 215, 157, 168, 52, 174, 112, 43, 172, 168, 228, 12, 65,
560        32, 7, 137, 2, 23, 201, 115, 89, 209, 151, 11, 86, 147, 213, 250, 164, 241, 244, 174, 66,
561        47, 165, 81, 114, 139, 189, 101, 212, 89, 149, 66, 219, 71, 186, 184, 228, 173, 170, 31, 5,
562        7, 144, 218, 34, 141, 15, 197, 201, 124, 159, 133, 70, 119, 16, 18, 50, 243, 5, 47, 247, 1,
563        145, 156, 73, 65, 244, 92, 190, 23, 37, 180, 126, 155, 198,
564    ];
565
566    /// Offset of the VAA, after the magic, version, trailing payload length, proof type and VAA
567    /// length.
568    const HERMES_VAA_START: usize = 4 + 1 + 1 + 1 + 1 + 2;
569    const HERMES_VAA_LEN: usize = 952;
570
571    fn hermes_feed(
572        feed_id: &str,
573        price: i64,
574        confidence: u64,
575        ema_price: i64,
576        ema_confidence: u64,
577    ) -> Feed {
578        let timestamp = 1_748_963_023;
579        Feed {
580            feed_id: feed_id.parse().unwrap(),
581            price: Price {
582                price,
583                confidence,
584                exponent: -8,
585                timestamp,
586            },
587            ema_price: Price {
588                price: ema_price,
589                confidence: ema_confidence,
590                exponent: -8,
591                timestamp,
592            },
593        }
594    }
595
596    #[test]
597    fn price_updates_parses_hermes_payload() {
598        let feeds = [
599            hermes_feed(
600                "0xeaa020c61cc479712813461ce153894a96a6c00b21ed0cfc2798d1f9a9e9c94a",
601                99_977_649,
602                110_030,
603                99_977_172,
604                107_265,
605            ),
606            hermes_feed(
607                "0x2b89b9dc8fdf9f34709a5b106b472f0f39bb6ca9ce04b0fd7f2e971688e2e53b",
608                100_066_541,
609                62_748,
610                100_058_850,
611                61_043,
612            ),
613        ];
614        let updates = PriceUpdates::from_bytes(Bytes::from_static(HERMES_PRICE_UPDATES)).unwrap();
615
616        assert_eq!(updates.feed_count(), 2);
617        assert_eq!(updates.feeds().collect::<Vec<_>>(), feeds);
618        assert_eq!(
619            updates.vaa(),
620            &HERMES_PRICE_UPDATES[HERMES_VAA_START..HERMES_VAA_START + HERMES_VAA_LEN],
621        );
622        assert!(updates.matches_set(&PriceFeedIdSet::from(feeds.map(|feed| feed.feed_id))));
623
624        let base64 = Base64::encode_string(HERMES_PRICE_UPDATES);
625        assert_eq!(PriceUpdates::from_base64(base64).unwrap(), updates);
626    }
627
628    #[test]
629    fn price_updates_rejects_malformed_hermes_payload() {
630        let modified = |index: usize, byte: u8| {
631            let mut bytes = HERMES_PRICE_UPDATES.to_vec();
632            bytes[index] = byte;
633            bytes
634        };
635        let mut trailing_data = HERMES_PRICE_UPDATES.to_vec();
636        trailing_data.push(0);
637        let message_start = HERMES_VAA_START + HERMES_VAA_LEN + 1;
638
639        let cases = [
640            ("invalid magic", modified(0, 0)),
641            ("invalid major version", modified(4, 2)),
642            ("invalid proof type", modified(7, 1)),
643            ("invalid message length", modified(message_start + 1, 84)),
644            ("invalid message type", modified(message_start + 2, 1)),
645            ("trailing data", trailing_data),
646            (
647                "truncated proof",
648                HERMES_PRICE_UPDATES[..HERMES_PRICE_UPDATES.len() - 1].to_vec(),
649            ),
650            (
651                "truncated VAA",
652                HERMES_PRICE_UPDATES[..HERMES_VAA_START + HERMES_VAA_LEN - 1].to_vec(),
653            ),
654        ];
655        for (name, bytes) in cases {
656            assert!(PriceUpdates::from_slice(&bytes).is_err(), "{name}");
657        }
658        assert!(PriceUpdate::from_bytes(Bytes::from_static(HERMES_PRICE_UPDATES)).is_err());
659    }
660}