Skip to main content

af_price_updates/
aftermath_writer.rs

1//! Serialization of Aftermath price updates, mirroring the parser in [`crate::aftermath`].
2//!
3//! The caller owns the buffer and the signing key: this module writes the payload and appends a
4//! signature that the caller made over [`UnsignedPriceUpdates::digest`].
5
6use crate::aftermath::{Feed, SIGNATURE_LEN, UPDATE_MAGIC};
7use crate::keccak::keccak256;
8use bytes::{BufMut, BytesMut};
9use std::io::{Error, ErrorKind};
10use std::ops::Range;
11
12/// Longest feed count encoding accepted by `Reader::take_vec_length`.
13const MAX_VEC_LENGTH_SIZE: usize = 5;
14
15impl Feed {
16    /// Length of the feed in a [`PriceUpdates`](crate::aftermath::PriceUpdates).
17    pub const fn serialized_size(&self) -> usize {
18        let property_count = self.confidence.is_some() as usize
19            + self.best_bid_price.is_some() as usize
20            + self.best_ask_price.is_some() as usize
21            + self.ema_price.is_some() as usize
22            + self.ema_confidence.is_some() as usize
23            + self.funding_rate.is_some() as usize
24            + self.funding_timestamp.is_some() as usize
25            + self.funding_rate_interval.is_some() as usize;
26        4 + 8 + 2 + 8 + 2 + 2 + 1 + property_count * (1 + 8)
27    }
28}
29
30/// An unsigned Aftermath update at the end of a caller's buffer, waiting for its signature.
31///
32/// [`Self::new`] writes the payload. Sign [`Self::digest`] with any secp256k1 implementation, then
33/// pass the signature to [`Self::append_signature`]. Dropping the value without appending a
34/// signature truncates the buffer to its length before the payload, so an unsigned payload is never
35/// left behind, e.g. when signing fails.
36#[derive(Debug)]
37#[must_use = "dropping an unsigned update removes its payload from the buffer"]
38pub struct UnsignedPriceUpdates<'b> {
39    buf: &'b mut BytesMut,
40    /// Length of `buf` before the payload; the buffer is truncated to it on drop.
41    payload_start: usize,
42}
43
44impl<'b> UnsignedPriceUpdates<'b> {
45    /// Length of a signed update of `feeds`: its payload plus the signature.
46    ///
47    /// Allocate this much spare capacity for [`Self::new`], plus any framing written before the
48    /// update, to serialize and sign it without reallocating.
49    pub fn signed_size(feeds: &[Feed]) -> usize {
50        let feeds_size: usize = feeds.iter().map(Feed::serialized_size).sum();
51        4 + 8 + vec_length_size(feeds.len()) + feeds_size + SIGNATURE_LEN
52    }
53    /// Validates `feeds` and appends the unsigned payload of an update to `buf`.
54    ///
55    /// Sign the returned [`Self::digest`] and append the signature with [`Self::append_signature`].
56    /// This crate never signs: the caller keeps the key and may use any secp256k1 implementation.
57    ///
58    /// First reserves [`Self::signed_size`] bytes, which is a no-op when `buf` already has that
59    /// much spare capacity; otherwise `buf` grows once. On error nothing is written.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`ErrorKind::InvalidInput`] if feed IDs are not strictly increasing.
64    ///
65    /// # Example
66    ///
67    /// ```
68    /// use af_price_updates::aftermath::{Feed, PriceFeedId, PriceUpdates, UnsignedPriceUpdates};
69    /// use bytes::{BufMut, BytesMut};
70    ///
71    /// let feeds = [Feed { feed_id: PriceFeedId(1), price: 42, ..Default::default() }];
72    /// let size = UnsignedPriceUpdates::signed_size(&feeds);
73    /// // A length prefix followed by the signed update, in a single allocation.
74    /// let mut buf = BytesMut::with_capacity(8 + size);
75    /// buf.put_u64(size as u64);
76    /// let unsigned = UnsignedPriceUpdates::new(&mut buf, 1_700_000_000_000_000, &feeds)?;
77    /// # let sign = |_: &[u8; 32]| ([0; 64], 0);
78    /// let (compact_signature, recovery_id) = sign(&unsigned.digest());
79    /// let update = unsigned.append_signature(&compact_signature, recovery_id);
80    ///
81    /// let updates = PriceUpdates::from_bytes(buf.freeze().slice(update))?;
82    /// assert!(updates.feeds().eq(feeds));
83    /// # Ok::<(), std::io::Error>(())
84    /// ```
85    pub fn new(buf: &'b mut BytesMut, timestamp: u64, feeds: &[Feed]) -> Result<Self, Error> {
86        if vec_length_size(feeds.len()) > MAX_VEC_LENGTH_SIZE {
87            return Err(Error::new(
88                ErrorKind::InvalidInput,
89                "Aftermath feed count is longer than five ULEB128 bytes",
90            ));
91        }
92        if !feeds.is_sorted_by(|a, b| a.feed_id < b.feed_id) {
93            return Err(Error::new(
94                ErrorKind::InvalidInput,
95                "Aftermath feed IDs are not strictly increasing",
96            ));
97        }
98        let size = Self::signed_size(feeds);
99        // A no-op for a buffer sized by the caller, and otherwise the only growth: the payload and
100        // the signature both fit afterwards.
101        buf.reserve(size);
102        let payload_start = buf.len();
103        buf.put_u32_le(UPDATE_MAGIC);
104        buf.put_u64_le(timestamp);
105        put_vec_length(buf, feeds.len());
106        for feed in feeds {
107            put_feed(buf, feed);
108        }
109        debug_assert_eq!(buf.len() - payload_start + SIGNATURE_LEN, size);
110        Ok(Self { buf, payload_start })
111    }
112    /// The payload that the signature must cover.
113    pub fn payload(&self) -> &[u8] {
114        &self.buf[self.payload_start..]
115    }
116    /// Keccak-256 of [`Self::payload`], the prehash to sign.
117    ///
118    /// Equal to [`PriceUpdates::digest`](crate::aftermath::PriceUpdates::digest) of the signed
119    /// update.
120    pub fn digest(&self) -> [u8; 32] {
121        keccak256(self.payload())
122    }
123    /// Appends a recoverable secp256k1 signature over [`Self::digest`], completing the update.
124    ///
125    /// `compact_signature` is `r ‖ s` as two 32-byte big-endian scalars, and `recovery_id` the
126    /// recovery ID byte. For example, with `k256` pass `&signature.to_bytes().into()` and
127    /// `recovery_id.to_byte()`; with `secp256k1`, `RecoverableSignature::serialize_compact`
128    /// returns both.
129    ///
130    /// Returns the range of the complete signed update within the buffer.
131    pub fn append_signature(
132        mut self,
133        compact_signature: &[u8; 64],
134        recovery_id: u8,
135    ) -> Range<usize> {
136        self.buf.put_slice(compact_signature);
137        self.buf.put_u8(recovery_id);
138        let update = self.payload_start..self.buf.len();
139        // The update is complete, so dropping `self` keeps it.
140        self.payload_start = self.buf.len();
141        update
142    }
143}
144
145impl Drop for UnsignedPriceUpdates<'_> {
146    fn drop(&mut self) {
147        self.buf.truncate(self.payload_start);
148    }
149}
150
151/// Mirrors `take_feed` in [`crate::aftermath`].
152fn put_feed(buf: &mut BytesMut, feed: &Feed) {
153    buf.put_u32_le(feed.feed_id.0);
154    buf.put_i64_le(feed.price);
155    buf.put_i16_le(feed.exponent);
156    buf.put_u64_le(feed.feed_update_timestamp);
157    buf.put_u16_le(feed.publisher_count);
158    buf.put_u16_le(feed.market_session.into());
159    // Indexed by property ID.
160    let properties: [Option<u64>; _] = [
161        feed.confidence.map(i64::cast_unsigned),
162        feed.best_bid_price.map(i64::cast_unsigned),
163        feed.best_ask_price.map(i64::cast_unsigned),
164        feed.ema_price.map(i64::cast_unsigned),
165        feed.ema_confidence,
166        feed.funding_rate.map(i64::cast_unsigned),
167        feed.funding_timestamp,
168        feed.funding_rate_interval,
169    ];
170    buf.put_u8(properties.iter().flatten().count() as u8);
171    for (property_id, value) in properties.into_iter().enumerate() {
172        if let Some(value) = value {
173            buf.put_u8(property_id as u8);
174            buf.put_u64_le(value);
175        }
176    }
177}
178
179/// Length of `length` in ULEB128.
180fn vec_length_size(length: usize) -> usize {
181    let bit_width = (usize::BITS - length.leading_zeros()) as usize;
182    bit_width.div_ceil(7).max(1)
183}
184
185/// Writes `length` in ULEB128, mirroring `Reader::take_vec_length`.
186fn put_vec_length(buf: &mut BytesMut, mut length: usize) {
187    while length >= 0x80 {
188        buf.put_u8((length & 0x7f) as u8 | 0x80);
189        length >>= 7;
190    }
191    buf.put_u8(length as u8);
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197    use crate::aftermath::{
198        MarketSession, PriceFeedId, PriceUpdates,
199        tests::{SIGNATURE, TIMESTAMP, feed_with_all_properties, mandatory_feed, signed_update},
200    };
201    use bytes::Bytes;
202
203    /// Appends the placeholder [`SIGNATURE`] of the parser tests.
204    fn append_placeholder_signature(unsigned: UnsignedPriceUpdates<'_>) -> Range<usize> {
205        let (compact_signature, recovery_id) = SIGNATURE.split_first_chunk().unwrap();
206        unsigned.append_signature(compact_signature, recovery_id[0])
207    }
208
209    /// Writes a signed update of `feeds` into an exactly sized buffer.
210    fn write_update(feeds: &[Feed]) -> BytesMut {
211        let size = UnsignedPriceUpdates::signed_size(feeds);
212        let mut buf = BytesMut::with_capacity(size);
213        let unsigned = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, feeds).unwrap();
214
215        assert_eq!(append_placeholder_signature(unsigned), 0..size);
216        buf
217    }
218
219    /// Mirrors `mandatory_feed(feed_id, 1, 0, 0)`.
220    fn feed(feed_id: u32) -> Feed {
221        Feed {
222            feed_id: PriceFeedId(feed_id),
223            price: 1,
224            feed_update_timestamp: TIMESTAMP,
225            publisher_count: 42,
226            ..Default::default()
227        }
228    }
229
230    /// A buffer holding `framing`, with exactly enough spare capacity for a signed update of
231    /// `feeds`.
232    fn framed_buffer(framing: &[u8], feeds: &[Feed]) -> BytesMut {
233        let mut buf =
234            BytesMut::with_capacity(framing.len() + UnsignedPriceUpdates::signed_size(feeds));
235        buf.put_slice(framing);
236        buf
237    }
238
239    #[test]
240    fn write_mandatory_fields() {
241        let feed = Feed {
242            feed_id: PriceFeedId(0x7856_3412),
243            price: -10,
244            exponent: -8,
245            market_session: MarketSession::Closed,
246            ..feed(0)
247        };
248
249        assert_eq!(
250            write_update(&[feed]),
251            signed_update(&[1], &mandatory_feed(0x7856_3412, -10, -8, 4))
252        );
253    }
254
255    #[test]
256    fn write_all_properties() {
257        let feed = Feed {
258            confidence: Some(100),
259            best_bid_price: Some(101),
260            best_ask_price: Some(102),
261            ema_price: Some(103),
262            ema_confidence: Some(104),
263            funding_rate: Some(105),
264            funding_timestamp: Some(106),
265            funding_rate_interval: Some(107),
266            ..feed(1)
267        };
268        let expected_feed = feed_with_all_properties();
269
270        assert_eq!(feed.serialized_size(), expected_feed.len());
271        assert_eq!(write_update(&[feed]), signed_update(&[1], &expected_feed));
272    }
273
274    #[test]
275    fn write_uleb128_feed_count() {
276        let feeds: Vec<Feed> = (0..128).map(feed).collect();
277        let expected_feeds: Vec<u8> = (0..128)
278            .flat_map(|feed_id| mandatory_feed(feed_id, 1, 0, 0))
279            .collect();
280
281        assert_eq!(
282            write_update(&feeds),
283            signed_update(&[0x80, 0x01], &expected_feeds)
284        );
285    }
286
287    #[test]
288    fn write_no_feeds() {
289        assert_eq!(write_update(&[]), signed_update(&[0], &[]));
290    }
291
292    #[test]
293    fn write_round_trips() {
294        let feeds = [
295            Feed {
296                best_ask_price: Some(i64::MAX),
297                funding_rate: Some(i64::MIN),
298                ..Feed::default()
299            },
300            Feed {
301                feed_id: PriceFeedId(7),
302                ..Default::default()
303            },
304            Feed {
305                feed_id: PriceFeedId(u32::MAX),
306                price: i64::MIN,
307                exponent: i16::MIN,
308                feed_update_timestamp: u64::MAX,
309                publisher_count: u16::MAX,
310                market_session: MarketSession::OverNight,
311                confidence: Some(-1),
312                best_bid_price: Some(-2),
313                best_ask_price: Some(-3),
314                ema_price: Some(-4),
315                ema_confidence: Some(u64::MAX),
316                funding_rate: Some(-5),
317                funding_timestamp: Some(6),
318                funding_rate_interval: Some(7),
319            },
320        ];
321        let updates = PriceUpdates::from_bytes(write_update(&feeds).freeze()).unwrap();
322
323        assert_eq!(updates.timestamp(), TIMESTAMP);
324        assert!(updates.feeds().eq(feeds));
325        assert_eq!(updates.signature(), &SIGNATURE);
326    }
327
328    #[test]
329    fn write_rejects_unsorted_feed_ids_without_writing() {
330        for feed_ids in [[1, 1], [5, 1]] {
331            let feeds = feed_ids.map(feed);
332            let mut buf = framed_buffer(b"framing", &feeds);
333            let err = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, &feeds).unwrap_err();
334
335            assert_eq!(err.kind(), ErrorKind::InvalidInput, "{feed_ids:?}");
336            assert_eq!(buf, &b"framing"[..], "{feed_ids:?}");
337        }
338    }
339
340    #[test]
341    fn write_after_framing_without_reallocating() {
342        let feeds = [feed(1), feed(5)];
343        let mut buf = framed_buffer(&[0; 8], &feeds);
344        let (capacity, ptr) = (buf.capacity(), buf.as_ptr());
345        let unsigned = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, &feeds).unwrap();
346        let update = append_placeholder_signature(unsigned);
347
348        assert_eq!(update, 8..buf.len());
349        assert_eq!(buf.len(), capacity);
350        assert_eq!(buf.capacity(), capacity);
351        assert_eq!(buf.as_ptr(), ptr);
352        assert_eq!(buf[..8], [0u8; 8]);
353        let updates = PriceUpdates::from_bytes(buf.freeze().slice(update)).unwrap();
354        assert!(updates.feeds().eq(feeds));
355    }
356
357    #[test]
358    fn write_grows_undersized_buffer() {
359        let feeds = [feed(1), feed(5)];
360        let mut buf = BytesMut::from(&b"framing"[..]);
361        let unsigned = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, &feeds).unwrap();
362        let update = append_placeholder_signature(unsigned);
363
364        assert_eq!(update.len(), UnsignedPriceUpdates::signed_size(&feeds));
365        assert_eq!(buf[..7], *b"framing");
366        assert_eq!(buf[update], write_update(&feeds));
367    }
368
369    #[test]
370    fn dropping_unsigned_update_removes_payload() {
371        let feeds = [feed(1)];
372        let mut buf = framed_buffer(b"framing", &feeds);
373        let unsigned = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, &feeds).unwrap();
374        assert!(!unsigned.payload().is_empty());
375        drop(unsigned);
376
377        assert_eq!(buf, &b"framing"[..]);
378    }
379
380    #[test]
381    fn digest_covers_payload() {
382        let feeds = [feed(1), feed(5)];
383        let mut buf = framed_buffer(b"framing", &feeds);
384        let unsigned = UnsignedPriceUpdates::new(&mut buf, TIMESTAMP, &feeds).unwrap();
385        let digest = unsigned.digest();
386
387        assert_eq!(digest, keccak256(unsigned.payload()));
388        let update = append_placeholder_signature(unsigned);
389        let updates = PriceUpdates::from_bytes(Bytes::copy_from_slice(&buf[update])).unwrap();
390        assert_eq!(updates.digest(), digest);
391        assert_eq!(updates.payload(), &buf[7..buf.len() - SIGNATURE_LEN]);
392    }
393
394    #[test]
395    fn vec_length_size_matches_written_length() {
396        for length in [0, 1, 0x7f, 0x80, 0x3fff, 0x4000, u32::MAX as usize] {
397            let mut buf = BytesMut::new();
398            put_vec_length(&mut buf, length);
399
400            assert_eq!(buf.len(), vec_length_size(length), "{length}");
401        }
402    }
403}