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