Skip to main content

df_hyperliquid_core/utils/sign/
msgpack.rs

1//! Msgpack as the venue hashes an L1 action: map keys in insertion order,
2//! never sorted, and a non-negative integer always unsigned.
3
4use std::borrow::Cow;
5
6use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};
7
8use crate::utils::json::Json;
9
10/// A msgpack value, the parts of the format an action uses. No floats.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Value {
13    /// `nil`; JSON `null`.
14    Nil,
15    /// `true` or `false`.
16    Bool(bool),
17    /// A non-negative integer, in the smallest unsigned encoding that holds it.
18    Uint(u64),
19    /// A negative integer. Non-negative values still encode as unsigned.
20    Int(i64),
21    /// A UTF-8 string.
22    Str(Cow<'static, str>),
23    /// An array, items in order.
24    Array(Vec<Value>),
25    /// A map, keys in insertion order.
26    Map(Map),
27}
28
29impl Value {
30    /// An array of anything that converts into a value.
31    #[must_use]
32    pub fn array<V: Into<Value>>(items: impl IntoIterator<Item = V>) -> Value {
33        Value::Array(items.into_iter().map(Into::into).collect())
34    }
35
36    /// The msgpack bytes; the same as [`encode`].
37    #[must_use]
38    pub fn to_msgpack(&self) -> Vec<u8> {
39        encode(self)
40    }
41
42    /// The same tree as JSON, keys in the same order: what is posted is what
43    /// was hashed.
44    #[must_use]
45    pub fn to_json(&self) -> Json {
46        match self {
47            Value::Nil => Json::Null,
48            Value::Bool(value) => Json::Bool(*value),
49            Value::Uint(number) => Json::Number(number.to_string()),
50            Value::Int(number) => Json::Number(number.to_string()),
51            Value::Str(text) => Json::String(text.to_string()),
52            Value::Array(items) => Json::Array(items.iter().map(Value::to_json).collect()),
53            Value::Map(map) => map.to_json(),
54        }
55    }
56}
57
58/// An ordered msgpack map: a list of key/value pairs in wire order.
59#[derive(Debug, Clone, PartialEq, Eq, Default)]
60pub struct Map(Vec<(Cow<'static, str>, Value)>);
61
62impl Map {
63    /// A map with no keys.
64    #[must_use]
65    pub const fn new() -> Self {
66        Map(Vec::new())
67    }
68
69    /// Appends `key` and `value` at the end. A key already present is not replaced; both are kept.
70    #[must_use]
71    pub fn put(mut self, key: impl Into<Cow<'static, str>>, value: impl Into<Value>) -> Self {
72        self.0.push((key.into(), value.into()));
73        self
74    }
75
76    /// [`Map::put`] when `value` is `Some`; leaves the key out when it is `None`.
77    #[must_use]
78    pub fn put_some(self, key: impl Into<Cow<'static, str>>, value: Option<impl Into<Value>>) -> Self {
79        match value {
80            Some(value) => self.put(key, value),
81            None => self,
82        }
83    }
84
85    /// How many key/value pairs it holds.
86    #[must_use]
87    pub fn len(&self) -> usize {
88        self.0.len()
89    }
90
91    /// Whether it holds no pairs.
92    #[must_use]
93    pub fn is_empty(&self) -> bool {
94        self.0.is_empty()
95    }
96
97    /// The pairs themselves, in wire order, for splicing one map into another.
98    pub fn into_pairs(self) -> impl Iterator<Item = (Cow<'static, str>, Value)> {
99        self.0.into_iter()
100    }
101
102    /// The keys in wire order.
103    pub fn keys(&self) -> impl Iterator<Item = &str> {
104        self.0.iter().map(|(key, _)| key.as_ref())
105    }
106
107    /// The value under `key`, the first if the key repeats.
108    #[must_use]
109    pub fn get(&self, key: &str) -> Option<&Value> {
110        self.0.iter().find(|(stored, _)| stored == key).map(|(_, value)| value)
111    }
112
113    /// The map as msgpack bytes, keys in wire order.
114    #[must_use]
115    pub fn to_msgpack(&self) -> Vec<u8> {
116        let mut out = Vec::new();
117        write_map(self, &mut out);
118        out
119    }
120
121    /// The map as a JSON object, keys in the same order.
122    #[must_use]
123    pub fn to_json(&self) -> Json {
124        Json::Object(self.0.iter().map(|(key, value)| (key.to_string(), value.to_json())).collect())
125    }
126}
127
128impl From<Map> for Value {
129    fn from(map: Map) -> Value {
130        Value::Map(map)
131    }
132}
133
134impl From<bool> for Value {
135    fn from(value: bool) -> Value {
136        Value::Bool(value)
137    }
138}
139
140impl From<u64> for Value {
141    fn from(value: u64) -> Value {
142        Value::Uint(value)
143    }
144}
145
146impl From<u32> for Value {
147    fn from(value: u32) -> Value {
148        Value::Uint(u64::from(value))
149    }
150}
151
152impl From<i64> for Value {
153    fn from(value: i64) -> Value {
154        Value::Int(value)
155    }
156}
157
158impl From<&'static str> for Value {
159    fn from(value: &'static str) -> Value {
160        Value::Str(Cow::Borrowed(value))
161    }
162}
163
164impl From<String> for Value {
165    fn from(value: String) -> Value {
166        Value::Str(Cow::Owned(value))
167    }
168}
169
170impl From<Cow<'static, str>> for Value {
171    fn from(value: Cow<'static, str>) -> Value {
172        Value::Str(value)
173    }
174}
175
176impl From<Vec<Value>> for Value {
177    fn from(value: Vec<Value>) -> Value {
178        Value::Array(value)
179    }
180}
181
182/// `value` as msgpack bytes.
183#[must_use]
184pub fn encode(value: &Value) -> Vec<u8> {
185    let mut out = Vec::new();
186    write(value, &mut out);
187    out
188}
189
190/// Appends `value` as msgpack bytes to `out`.
191pub fn write(value: &Value, out: &mut Vec<u8>) {
192    match value {
193        Value::Nil => out.push(0xc0),
194        Value::Bool(false) => out.push(0xc2),
195        Value::Bool(true) => out.push(0xc3),
196        Value::Uint(number) => write_uint(*number, out),
197        Value::Int(number) => write_int(*number, out),
198        Value::Str(text) => write_str(text, out),
199        Value::Array(items) => {
200            write_len(items.len(), 0x90, 0xdc, 0xdd, out);
201            for item in items {
202                write(item, out);
203            }
204        }
205        Value::Map(map) => write_map(map, out),
206    }
207}
208
209fn write_map(map: &Map, out: &mut Vec<u8>) {
210    write_len(map.0.len(), 0x80, 0xde, 0xdf, out);
211    for (key, value) in &map.0 {
212        write_str(key, out);
213        write(value, out);
214    }
215}
216
217fn write_len(len: usize, fixed: u8, wide16: u8, wide32: u8, out: &mut Vec<u8>) {
218    if len <= 15 {
219        out.push(fixed | len as u8);
220    } else if let Ok(len) = u16::try_from(len) {
221        out.push(wide16);
222        out.extend_from_slice(&len.to_be_bytes());
223    } else {
224        out.push(wide32);
225        out.extend_from_slice(&(len as u32).to_be_bytes());
226    }
227}
228
229fn write_str(text: &str, out: &mut Vec<u8>) {
230    let bytes = text.as_bytes();
231    if bytes.len() <= 31 {
232        out.push(0xa0 | bytes.len() as u8);
233    } else if let Ok(len) = u8::try_from(bytes.len()) {
234        out.push(0xd9);
235        out.push(len);
236    } else if let Ok(len) = u16::try_from(bytes.len()) {
237        out.push(0xda);
238        out.extend_from_slice(&len.to_be_bytes());
239    } else {
240        out.push(0xdb);
241        out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
242    }
243    out.extend_from_slice(bytes);
244}
245
246fn write_uint(number: u64, out: &mut Vec<u8>) {
247    if number <= 0x7f {
248        out.push(number as u8);
249    } else if let Ok(byte) = u8::try_from(number) {
250        out.push(0xcc);
251        out.push(byte);
252    } else if let Ok(short) = u16::try_from(number) {
253        out.push(0xcd);
254        out.extend_from_slice(&short.to_be_bytes());
255    } else if let Ok(word) = u32::try_from(number) {
256        out.push(0xce);
257        out.extend_from_slice(&word.to_be_bytes());
258    } else {
259        out.push(0xcf);
260        out.extend_from_slice(&number.to_be_bytes());
261    }
262}
263
264fn write_int(number: i64, out: &mut Vec<u8>) {
265    if let Ok(unsigned) = u64::try_from(number) {
266        write_uint(unsigned, out);
267    } else if number >= -32 {
268        out.push(number as u8);
269    } else if let Ok(byte) = i8::try_from(number) {
270        out.push(0xd0);
271        out.extend_from_slice(&byte.to_be_bytes());
272    } else if let Ok(short) = i16::try_from(number) {
273        out.push(0xd1);
274        out.extend_from_slice(&short.to_be_bytes());
275    } else if let Ok(word) = i32::try_from(number) {
276        out.push(0xd2);
277        out.extend_from_slice(&word.to_be_bytes());
278    } else {
279        out.push(0xd3);
280        out.extend_from_slice(&number.to_be_bytes());
281    }
282}
283
284impl Serialize for Value {
285    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
286        match self {
287            Value::Nil => serializer.serialize_unit(),
288            Value::Bool(value) => serializer.serialize_bool(*value),
289            Value::Uint(number) => serializer.serialize_u64(*number),
290            Value::Int(number) => serializer.serialize_i64(*number),
291            Value::Str(text) => serializer.serialize_str(text),
292            Value::Array(items) => {
293                let mut sequence = serializer.serialize_seq(Some(items.len()))?;
294                for item in items {
295                    sequence.serialize_element(item)?;
296                }
297                sequence.end()
298            }
299            Value::Map(map) => map.serialize(serializer),
300        }
301    }
302}
303
304impl Serialize for Map {
305    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
306        let mut entries = serializer.serialize_map(Some(self.0.len()))?;
307        for (key, value) in &self.0 {
308            entries.serialize_entry(key.as_ref(), value)?;
309        }
310        entries.end()
311    }
312}
313
314#[cfg(test)]
315#[path = "tests/msgpack.rs"]
316mod tests;