serde_xrpl/
utils.rs

1use std::str::FromStr;
2
3use super::error::{Error, Result};
4use bs58::Alphabet;
5use rust_decimal::{prelude::ToPrimitive, Decimal, MathematicalOps};
6use serde::{ser, Serialize};
7
8pub fn encode_variable_length(length: usize) -> Vec<u8> {
9    let mut len_bytes = [0u8; 3];
10    if length <= 192 {
11        return vec![length as u8];
12    } else if length <= 12480 {
13        let length_a = length - 193;
14        len_bytes[0] = 193 + (length_a >> 8usize) as u8;
15        len_bytes[1] = (length_a & 0xff) as u8;
16        return vec![len_bytes[0], len_bytes[1]];
17    } else if length <= 918744 {
18        let length_a = length - 12481;
19        len_bytes[0] = 241 + (length_a >> 16usize) as u8;
20        len_bytes[1] = ((length_a >> 8isize) & 0xff) as u8;
21        len_bytes[2] = (length_a & 0xff) as u8;
22        return vec![len_bytes[0], len_bytes[1], len_bytes[2]];
23    }
24    panic!("overflow error");
25}
26
27pub fn encode_field_id(type_code: u8, field_code: u8) -> Vec<u8> {
28    if type_code < 16 && field_code < 16 {
29        let field_id = type_code << 4 | field_code;
30        return vec![field_id as u8];
31    } else if type_code < 16 && field_code >= 16 {
32        let field_id = type_code << 4;
33        return vec![field_id as u8, field_code as u8];
34    } else if type_code >= 16 && field_code < 16 {
35        return vec![field_code as u8, type_code as u8];
36    }
37    vec![0u8, type_code, field_code]
38}
39
40pub const XRPL_ALPHABET: Alphabet = *bs58::Alphabet::RIPPLE;
41
42pub fn decode_base58(b58_string: &str, prefix: &[u8]) -> Result<Vec<u8>> {
43    let prefix_len = prefix.len();
44    let decoded = bs58::decode(b58_string)
45        .with_alphabet(&XRPL_ALPHABET)
46        .with_check(None)
47        .into_vec()
48        .map_err(|e| Error::InvalidAddress)?;
49    if &decoded[..prefix_len] != prefix {
50        Err(Error::InvalidAddress)
51    } else {
52        Ok(decoded[prefix_len..].to_vec())
53    }
54}
55
56pub fn encode_currency_code(currency_code: &str) -> Vec<u8> {
57    if currency_code.as_bytes().len() == 3 {
58        return [
59            [0u8; 12].to_vec(),
60            currency_code.as_bytes().to_vec(),
61            [0u8; 5].to_vec(),
62        ]
63        .concat();
64    }
65    if currency_code.as_bytes().len() == 40 {
66        return hex::decode(&currency_code).unwrap()
67    }
68    panic!("invalid currency code with length: {}", currency_code.as_bytes().len())
69}
70
71pub fn encode_issued_currency_amount(
72    amount: &str,
73    currency: &str,
74    issuer: &str,
75) -> Result<Vec<u8>> {
76    let encoded_address = decode_base58(issuer, &[0x00])?;
77
78    let mut decimal_amount = Decimal::from_str(amount)
79        .map_err(|e| Error::InvalidIssuedCurrencyAmount(format!("{:?}", e)))?;
80
81    let mut encoded_amount;
82
83    if decimal_amount.is_zero() {
84        encoded_amount = [0u8; 8];
85        encoded_amount[0] |= 0x80;
86    } else {
87        // Rescale decimal to normalise the mantisssa between 10e15 (1000000000000000) to 10e16-1 (9999999999999999) inclusive.
88        let e = decimal_amount.log10().floor().to_u32().unwrap();
89        decimal_amount.rescale(15 - e);
90        encoded_amount = decimal_amount.mantissa().to_u64().unwrap().to_be_bytes();
91        encoded_amount[0] |= 0x80;
92        if decimal_amount.is_sign_positive() {
93            encoded_amount[0] |= 0x40;
94        }
95        let exponent = e as i32 - 15;
96        let exponent_bytes = (97 + exponent).to_u8().unwrap();
97        encoded_amount[0] |= exponent_bytes >> 2u8;
98        encoded_amount[1] |= (exponent_bytes & 0x03) << 6u8;
99    }
100
101    let encoded_currency = encode_currency_code(currency);
102
103    Ok([encoded_amount.to_vec(), encoded_currency, encoded_address]
104        .concat()
105        .to_vec())
106}
107
108#[derive(Default)]
109pub struct StringSerializer {
110    pub value: Option<String>,
111}
112
113impl<'a> ser::Serializer for &'a mut StringSerializer {
114    // The output type produced by this `Serializer` during successful
115    // serialization. Most serializers that produce text or binary output should
116    // set `Ok = ()` and serialize into an `io::Write` or buffer contained
117    // within the `Serializer` instance, as happens here. Serializers that build
118    // in-memory data structures may be simplified by using `Ok` to propagate
119    // the data structure around.
120    type Ok = ();
121
122    // The error type when some error occurs during serialization.
123    type Error = Error;
124
125    // Associated types for keeping track of additional state while serializing
126    // compound data structures like sequences and maps. In this case no
127    // additional state is required beyond what is already stored in the
128    // Serializer struct.
129    type SerializeSeq = Self;
130    type SerializeTuple = Self;
131    type SerializeTupleStruct = Self;
132    type SerializeTupleVariant = Self;
133    type SerializeMap = Self;
134    type SerializeStruct = Self;
135    type SerializeStructVariant = Self;
136
137    // Here we go with the simple methods. The following 12 methods receive one
138    // of the primitive types of the data model and map it to JSON by appending
139    // into the output string.
140    fn serialize_bool(self, v: bool) -> Result<()> {
141        unimplemented!()
142    }
143
144    // JSON does not distinguish between different sizes of integers, so all
145    // signed integers will be serialized the same and all unsigned integers
146    // will be serialized the same. Other formats, especially compact binary
147    // formats, may need independent logic for the different sizes.
148    fn serialize_i8(self, v: i8) -> Result<()> {
149        unimplemented!()
150    }
151
152    fn serialize_i16(self, v: i16) -> Result<()> {
153        unimplemented!()
154    }
155
156    fn serialize_i32(self, v: i32) -> Result<()> {
157        unimplemented!()
158    }
159
160    // Not particularly efficient but this is example code anyway. A more
161    // performant approach would be to use the `itoa` crate.
162    fn serialize_i64(self, v: i64) -> Result<()> {
163        unimplemented!()
164    }
165
166    fn serialize_u8(self, v: u8) -> Result<()> {
167        unimplemented!()
168    }
169
170    fn serialize_u16(self, v: u16) -> Result<()> {
171        unimplemented!()
172    }
173
174    fn serialize_u32(self, v: u32) -> Result<()> {
175        unimplemented!()
176    }
177
178    fn serialize_u64(self, v: u64) -> Result<()> {
179        unimplemented!()
180    }
181
182    fn serialize_f32(self, v: f32) -> Result<()> {
183        unimplemented!()
184    }
185
186    fn serialize_f64(self, v: f64) -> Result<()> {
187        unimplemented!()
188    }
189
190    // Serialize a char as a single-character string. Other formats may
191    // represent this differently.
192    fn serialize_char(self, v: char) -> Result<()> {
193        unimplemented!()
194    }
195
196    // This only works for strings that don't require escape sequences but you
197    // get the idea. For example it would emit invalid JSON if the input string
198    // contains a '"' character.
199    fn serialize_str(self, v: &str) -> Result<()> {
200        self.value = Some(v.to_owned());
201        Ok(())
202    }
203
204    // Serialize a byte array as an array of bytes. Could also use a base64
205    // string here. Binary formats will typically represent byte arrays more
206    // compactly.
207    fn serialize_bytes(self, v: &[u8]) -> Result<()> {
208        unimplemented!()
209    }
210
211    // An absent optional is represented as the JSON `null`.
212    fn serialize_none(self) -> Result<()> {
213        unimplemented!()
214    }
215
216    // A present optional is represented as just the contained value. Note that
217    // this is a lossy representation. For example the values `Some(())` and
218    // `None` both serialize as just `null`. Unfortunately this is typically
219    // what people expect when working with JSON. Other formats are encouraged
220    // to behave more intelligently if possible.
221    fn serialize_some<T>(self, value: &T) -> Result<()>
222    where
223        T: ?Sized + Serialize,
224    {
225        unimplemented!()
226    }
227
228    // In Serde, unit means an anonymous value containing no data. Map this to
229    // JSON as `null`.
230    fn serialize_unit(self) -> Result<()> {
231        unimplemented!()
232    }
233
234    // Unit struct means a named value containing no data. Again, since there is
235    // no data, map this to JSON as `null`. There is no need to serialize the
236    // name in most formats.
237    fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
238        unimplemented!()
239    }
240
241    // When serializing a unit variant (or any other kind of variant), formats
242    // can choose whether to keep track of it by index or by name. Binary
243    // formats typically use the index of the variant and human-readable formats
244    // typically use the name.
245    fn serialize_unit_variant(
246        self,
247        _name: &'static str,
248        _variant_index: u32,
249        variant: &'static str,
250    ) -> Result<()> {
251        unimplemented!()
252    }
253
254    // As is done here, serializers are encouraged to treat newtype structs as
255    // insignificant wrappers around the data they contain.
256    fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()>
257    where
258        T: ?Sized + Serialize,
259    {
260        unimplemented!()
261    }
262
263    // Note that newtype variant (and all of the other variant serialization
264    // methods) refer exclusively to the "externally tagged" enum
265    // representation.
266    //
267    // Serialize this to JSON in externally tagged form as `{ NAME: VALUE }`.
268    fn serialize_newtype_variant<T>(
269        self,
270        _name: &'static str,
271        _variant_index: u32,
272        variant: &'static str,
273        value: &T,
274    ) -> Result<()>
275    where
276        T: ?Sized + Serialize,
277    {
278        unimplemented!()
279    }
280
281    // Now we get to the serialization of compound types.
282    //
283    // The start of the sequence, each value, and the end are three separate
284    // method calls. This one is responsible only for serializing the start,
285    // which in JSON is `[`.
286    //
287    // The length of the sequence may or may not be known ahead of time. This
288    // doesn't make a difference in JSON because the length is not represented
289    // explicitly in the serialized form. Some serializers may only be able to
290    // support sequences for which the length is known up front.
291    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
292        unimplemented!()
293    }
294
295    // Tuples look just like sequences in JSON. Some formats may be able to
296    // represent tuples more efficiently by omitting the length, since tuple
297    // means that the corresponding `Deserialize implementation will know the
298    // length without needing to look at the serialized data.
299    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> {
300        unimplemented!()
301    }
302
303    // Tuple structs look just like sequences in JSON.
304    fn serialize_tuple_struct(
305        self,
306        _name: &'static str,
307        len: usize,
308    ) -> Result<Self::SerializeTupleStruct> {
309        unimplemented!()
310    }
311
312    // Tuple variants are represented in JSON as `{ NAME: [DATA...] }`. Again
313    // this method is only responsible for the externally tagged representation.
314    fn serialize_tuple_variant(
315        self,
316        _name: &'static str,
317        _variant_index: u32,
318        variant: &'static str,
319        _len: usize,
320    ) -> Result<Self::SerializeTupleVariant> {
321        unimplemented!()
322    }
323
324    // Maps are represented in JSON as `{ K: V, K: V, ... }`.
325    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
326        unimplemented!()
327    }
328
329    // Structs look just like maps in JSON. In particular, JSON requires that we
330    // serialize the field names of the struct. Other formats may be able to
331    // omit the field names when serializing structs because the corresponding
332    // Deserialize implementation is required to know what the keys are without
333    // looking at the serialized data.
334    fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> {
335        unimplemented!()
336    }
337
338    // Struct variants are represented in JSON as `{ NAME: { K: V, ... } }`.
339    // This is the externally tagged representation.
340    fn serialize_struct_variant(
341        self,
342        _name: &'static str,
343        _variant_index: u32,
344        variant: &'static str,
345        _len: usize,
346    ) -> Result<Self::SerializeStructVariant> {
347        unimplemented!()
348    }
349}
350
351// The following 7 impls deal with the serialization of compound types like
352// sequences and maps. Serialization of such types is begun by a Serializer
353// method and followed by zero or more calls to serialize individual elements of
354// the compound type and one call to end the compound type.
355//
356// This impl is SerializeSeq so these methods are called after `serialize_seq`
357// is called on the Serializer.
358impl<'a> ser::SerializeSeq for &'a mut StringSerializer {
359    // Must match the `Ok` type of the serializer.
360    type Ok = ();
361    // Must match the `Error` type of the serializer.
362    type Error = Error;
363
364    // Serialize a single element of the sequence.
365    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
366    where
367        T: ?Sized + Serialize,
368    {
369        unimplemented!()
370    }
371
372    // Close the sequence.
373    fn end(self) -> Result<()> {
374        unimplemented!()
375    }
376}
377
378// Same thing but for tuples.
379impl<'a> ser::SerializeTuple for &'a mut StringSerializer {
380    type Ok = ();
381    type Error = Error;
382
383    fn serialize_element<T>(&mut self, value: &T) -> Result<()>
384    where
385        T: ?Sized + Serialize,
386    {
387        unimplemented!()
388    }
389
390    fn end(self) -> Result<()> {
391        unimplemented!()
392    }
393}
394
395// Same thing but for tuple structs.
396impl<'a> ser::SerializeTupleStruct for &'a mut StringSerializer {
397    type Ok = ();
398    type Error = Error;
399
400    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
401    where
402        T: ?Sized + Serialize,
403    {
404        unimplemented!()
405    }
406
407    fn end(self) -> Result<()> {
408        unimplemented!()
409    }
410}
411
412impl<'a> ser::SerializeTupleVariant for &'a mut StringSerializer {
413    type Ok = ();
414    type Error = Error;
415
416    fn serialize_field<T>(&mut self, value: &T) -> Result<()>
417    where
418        T: ?Sized + Serialize,
419    {
420        unimplemented!()
421    }
422
423    fn end(self) -> Result<()> {
424        unimplemented!()
425    }
426}
427
428// Some `Serialize` types are not able to hold a key and value in memory at the
429// same time so `SerializeMap` implementations are required to support
430// `serialize_key` and `serialize_value` individually.
431//
432// There is a third optional method on the `SerializeMap` trait. The
433// `serialize_entry` method allows serializers to optimize for the case where
434// key and value are both available simultaneously. In JSON it doesn't make a
435// difference so the default behavior for `serialize_entry` is fine.
436impl<'a> ser::SerializeMap for &'a mut StringSerializer {
437    type Ok = ();
438    type Error = Error;
439
440    // The Serde data model allows map keys to be any serializable type. JSON
441    // only allows string keys so the implementation below will produce invalid
442    // JSON if the key serializes as something other than a string.
443    //
444    // A real JSON serializer would need to validate that map keys are strings.
445    // This can be done by using a different Serializer to serialize the key
446    // (instead of `&mut **self`) and having that other serializer only
447    // implement `serialize_str` and return an error on any other data type.
448    fn serialize_key<T>(&mut self, key: &T) -> Result<()>
449    where
450        T: ?Sized + Serialize,
451    {
452        unimplemented!()
453    }
454
455    // It doesn't make a difference whether the colon is printed at the end of
456    // `serialize_key` or at the beginning of `serialize_value`. In this case
457    // the code is a bit simpler having it here.
458    fn serialize_value<T>(&mut self, value: &T) -> Result<()>
459    where
460        T: ?Sized + Serialize,
461    {
462        unimplemented!()
463    }
464
465    fn end(self) -> Result<()> {
466        unimplemented!()
467    }
468}
469
470// Structs are like maps in which the keys are constrained to be compile-time
471// constant strings.
472impl<'a> ser::SerializeStruct for &'a mut StringSerializer {
473    type Ok = ();
474    type Error = Error;
475
476    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
477    where
478        T: ?Sized + Serialize,
479    {
480        unimplemented!()
481    }
482
483    fn end(self) -> Result<()> {
484        unimplemented!()
485    }
486}
487
488// Similar to `SerializeTupleVariant`, here the `end` method is responsible for
489// closing both of the curly braces opened by `serialize_struct_variant`.
490impl<'a> ser::SerializeStructVariant for &'a mut StringSerializer {
491    type Ok = ();
492    type Error = Error;
493
494    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>
495    where
496        T: ?Sized + Serialize,
497    {
498        unimplemented!()
499    }
500
501    fn end(self) -> Result<()> {
502        unimplemented!()
503    }
504}