ns_protocol/
ns.rs

1use ciborium_io::{Read, Write};
2use finl_unicode::categories::CharacterCategories;
3use serde::{de, ser, Deserialize, Serialize};
4use std::{convert::From, fmt::Debug};
5
6pub use ciborium::{
7    from_reader, into_writer, tag,
8    value::{Error, Value},
9};
10
11use crate::ed25519::{self, Signer};
12
13pub type NSTag = tag::Required<Name, 53>;
14pub type NSTagRef<'a> = tag::Required<&'a Name, 53>;
15pub const MAX_NAME_BYTES: usize = 520;
16pub(crate) const NS_PREFIX: [u8; 3] = [0xd8, 0x35, 0x84]; // d835: tag(53), 84: array(4)
17
18#[derive(Clone, PartialEq, Debug, Default)]
19pub struct Name {
20    pub name: String,
21    pub sequence: u64,
22    pub service: Service,
23    pub signatures: Vec<Bytes64>,
24}
25
26#[derive(Clone, PartialEq, Debug, Default)]
27pub struct Service {
28    pub code: u64,
29    pub operations: Vec<Operation>,
30    pub attesters: Option<Vec<String>>, // attester's name
31}
32
33#[derive(Clone, PartialEq, Debug)]
34pub struct Operation {
35    pub subcode: u16,
36    pub params: Value,
37}
38
39impl core::default::Default for Operation {
40    fn default() -> Self {
41        Operation {
42            subcode: 0,
43            params: Value::Array(vec![]),
44        }
45    }
46}
47
48#[derive(Clone, PartialEq, Debug)]
49pub(crate) struct IntValue<'a>(pub &'a Value);
50impl<'a> IntValue<'a> {
51    fn to_int(&self) -> Result<ciborium::value::Integer, Error> {
52        self.0.as_integer().ok_or_else(|| {
53            Error::Custom(format!(
54                "IntValue: expected integer, got {}",
55                kind_of_value(self.0)
56            ))
57        })
58    }
59}
60
61impl TryFrom<&IntValue<'_>> for u64 {
62    type Error = Error;
63
64    fn try_from(value: &IntValue) -> Result<Self, Self::Error> {
65        u64::try_from(value.to_int()?)
66            .map_err(|err| Error::Custom(format!("IntValue: expected u64, error: {:?}", err)))
67    }
68}
69
70impl TryFrom<&IntValue<'_>> for u32 {
71    type Error = Error;
72
73    fn try_from(value: &IntValue) -> Result<Self, Self::Error> {
74        u32::try_from(value.to_int()?)
75            .map_err(|err| Error::Custom(format!("IntValue: expected u64, error: {:?}", err)))
76    }
77}
78
79impl TryFrom<&IntValue<'_>> for u16 {
80    type Error = Error;
81
82    fn try_from(value: &IntValue) -> Result<Self, Self::Error> {
83        u16::try_from(value.to_int()?)
84            .map_err(|err| Error::Custom(format!("IntValue: expected u64, error: {:?}", err)))
85    }
86}
87
88impl TryFrom<&IntValue<'_>> for u8 {
89    type Error = Error;
90
91    fn try_from(value: &IntValue) -> Result<Self, Self::Error> {
92        u8::try_from(value.to_int()?)
93            .map_err(|err| Error::Custom(format!("IntValue: expected u64, error: {:?}", err)))
94    }
95}
96
97#[derive(Clone, PartialEq, Eq, Debug, Hash, Default)]
98pub struct Bytes32(pub [u8; 32]);
99
100impl From<[u8; 32]> for Bytes32 {
101    fn from(value: [u8; 32]) -> Self {
102        Bytes32(value)
103    }
104}
105
106impl From<&[u8; 32]> for Bytes32 {
107    fn from(value: &[u8; 32]) -> Self {
108        Bytes32(value.to_owned())
109    }
110}
111
112impl From<&Bytes32> for Vec<u8> {
113    fn from(value: &Bytes32) -> Self {
114        value.to_vec()
115    }
116}
117
118impl From<Bytes32> for Vec<u8> {
119    fn from(value: Bytes32) -> Self {
120        value.to_vec()
121    }
122}
123
124impl TryFrom<&[u8]> for Bytes32 {
125    type Error = Error;
126
127    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
128        if value.len() != 32 {
129            Err(Error::Custom(format!(
130                "Bytes32: expected value length is 32, got {:?}",
131                value.len()
132            )))
133        } else {
134            let mut bytes = [0u8; 32];
135            bytes.copy_from_slice(value);
136            Ok(Bytes32(bytes))
137        }
138    }
139}
140
141impl TryFrom<&Vec<u8>> for Bytes32 {
142    type Error = Error;
143    fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
144        Bytes32::try_from(value.as_slice())
145    }
146}
147
148impl TryFrom<Vec<u8>> for Bytes32 {
149    type Error = Error;
150    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
151        Bytes32::try_from(value.as_slice())
152    }
153}
154
155impl Bytes32 {
156    pub fn to_vec(&self) -> Vec<u8> {
157        self.0.to_vec()
158    }
159
160    pub fn vec_into(values: &[Self]) -> Vec<Vec<u8>> {
161        values.iter().map(|v| v.to_vec()).collect()
162    }
163
164    pub fn vec_try_from(values: &[Vec<u8>]) -> Result<Vec<Self>, Error> {
165        values.iter().map(Bytes32::try_from).collect()
166    }
167
168    pub fn vec_try_from_value(value: &Value) -> Result<Vec<Self>, Error> {
169        value
170            .as_array()
171            .ok_or_else(|| {
172                Error::Custom(format!(
173                    "Bytes32: expected array, got {}",
174                    kind_of_value(value)
175                ))
176            })?
177            .iter()
178            .map(Bytes32::try_from)
179            .collect::<Result<Vec<Bytes32>, Error>>()
180    }
181}
182
183#[derive(Clone, PartialEq, Eq, Debug, Hash)]
184pub struct Bytes64(pub [u8; 64]);
185
186impl core::default::Default for Bytes64 {
187    fn default() -> Self {
188        Bytes64([0u8; 64])
189    }
190}
191
192impl From<[u8; 64]> for Bytes64 {
193    fn from(value: [u8; 64]) -> Self {
194        Bytes64(value)
195    }
196}
197
198impl From<&[u8; 64]> for Bytes64 {
199    fn from(value: &[u8; 64]) -> Self {
200        Bytes64(value.to_owned())
201    }
202}
203
204impl From<&Bytes64> for Vec<u8> {
205    fn from(value: &Bytes64) -> Self {
206        value.to_vec()
207    }
208}
209
210impl From<Bytes64> for Vec<u8> {
211    fn from(value: Bytes64) -> Self {
212        value.to_vec()
213    }
214}
215
216impl TryFrom<&[u8]> for Bytes64 {
217    type Error = Error;
218
219    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
220        if value.len() != 64 {
221            Err(Error::Custom(format!(
222                "Bytes64: expected value length is 64, got {:?}",
223                value.len()
224            )))
225        } else {
226            let mut bytes = [0u8; 64];
227            bytes.copy_from_slice(value);
228            Ok(Bytes64(bytes))
229        }
230    }
231}
232
233impl TryFrom<&Vec<u8>> for Bytes64 {
234    type Error = Error;
235    fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
236        Bytes64::try_from(value.as_slice())
237    }
238}
239
240impl Bytes64 {
241    pub fn to_vec(&self) -> Vec<u8> {
242        self.0.to_vec()
243    }
244
245    pub fn vec_into(values: &[Self]) -> Vec<Vec<u8>> {
246        values.iter().map(|v| v.to_vec()).collect()
247    }
248
249    pub fn vec_try_from(values: &[Vec<u8>]) -> Result<Vec<Self>, Error> {
250        values.iter().map(Bytes64::try_from).collect()
251    }
252
253    pub fn vec_try_from_value(value: &Value) -> Result<Vec<Self>, Error> {
254        value
255            .as_array()
256            .ok_or_else(|| {
257                Error::Custom(format!(
258                    "Bytes64: expected array, got {}",
259                    kind_of_value(value)
260                ))
261            })?
262            .iter()
263            .map(Bytes64::try_from)
264            .collect::<Result<Vec<Bytes64>, Error>>()
265    }
266}
267
268// PublicKeyParams is Ed25519 Multisignatures with threshold,
269// every public key can be FROST (Flexible Round-Optimised Schnorr Threshold signatures)
270// see: https://github.com/ZcashFoundation/frost
271#[derive(Clone, PartialEq, Eq, Debug, Default)]
272pub struct PublicKeyParams {
273    pub public_keys: Vec<Bytes32>,
274    pub threshold: Option<u8>, // default to public_keys.len()
275    pub kind: Option<u8>,      // default to 0: ed25519
276}
277
278#[derive(Clone, PartialEq, Eq, Debug, Default)]
279pub enum ThresholdLevel {
280    Single,
281    #[default]
282    Default, // DefaultLevel = threshold, 1 <= DefaultLevel <= public_keys.len()
283    Strict, // StrictLevel = threshold + 1, 1 <= StrictLevel <= public_keys.len()
284    All,    // AllLevel = public_keys.len()
285}
286
287impl PublicKeyParams {
288    pub fn validate(&self) -> Result<(), Error> {
289        if self.public_keys.is_empty() {
290            return Err(Error::Custom(
291                "PublicKeyParams: expected at least one public key".to_string(),
292            ));
293        }
294
295        if let Some(threshold) = self.threshold {
296            if threshold == 0 {
297                return Err(Error::Custom(
298                    "PublicKeyParams: threshold must be greater than 0".to_string(),
299                ));
300            }
301            if threshold > self.public_keys.len() as u8 {
302                return Err(Error::Custom(format!(
303                    "PublicKeyParams: threshold {} is greater than number of public keys {}",
304                    threshold,
305                    self.public_keys.len()
306                )));
307            }
308        }
309        if let Some(kind) = self.kind {
310            if kind != 0 {
311                return Err(Error::Custom(format!(
312                    "PublicKeyParams: unsupported public key kind {}",
313                    kind
314                )));
315            }
316        }
317        let mut public_keys = self.public_keys.clone();
318        public_keys.dedup();
319        if public_keys.len() != self.public_keys.len() {
320            return Err(Error::Custom(
321                "PublicKeyParams: duplicate public_keys".to_string(),
322            ));
323        }
324
325        Ok(())
326    }
327
328    pub fn verifying_threshold(&self, level: ThresholdLevel) -> u8 {
329        match level {
330            ThresholdLevel::Single => 1,
331            ThresholdLevel::Default => self.threshold.unwrap_or(self.public_keys.len() as u8),
332            ThresholdLevel::Strict => {
333                let full = self.public_keys.len() as u8;
334                let l = self.threshold.map(|v| v + 1).unwrap_or(full);
335                if l > full {
336                    full
337                } else {
338                    l
339                }
340            }
341            ThresholdLevel::All => self.public_keys.len() as u8,
342        }
343    }
344}
345
346// name should be valid utf-8 string, not empty, not longer than 64 bytes, and not contain any of the following characters: uppercase letters, punctuations, separators, marks, symbols, and other control characters, format characters, surrogates, unassigned characters and private use characters.
347// https://docs.rs/finl_unicode/latest/finl_unicode/categories/trait.CharacterCategories.html
348pub fn valid_name(name: &str) -> bool {
349    let mut size = 0;
350    // let cs = Graphemes::new(name);
351    for c in name.chars() {
352        size += 1;
353        if size > 64 {
354            return false;
355        }
356        if c.is_letter_uppercase()
357            || c.is_punctuation()
358            || c.is_separator()
359            || c.is_mark()
360            || c.is_symbol()
361            || c.is_other()
362        {
363            return false;
364        }
365    }
366
367    !name.is_empty()
368}
369
370impl Name {
371    pub fn decode_from<R: Read>(r: R) -> Result<Self, Error>
372    where
373        R::Error: core::fmt::Debug,
374    {
375        let value: NSTag = from_reader(r)
376            .map_err(|err| Error::Custom(format!("Name: decode_from error, {:?}", err)))?;
377        Ok(value.0)
378    }
379
380    pub fn encode_to<W: Write>(&self, w: W) -> Result<(), Error>
381    where
382        W::Error: core::fmt::Debug,
383    {
384        let v: NSTagRef = tag::Required(self);
385        into_writer(&v, w)
386            .map_err(|err| Error::Custom(format!("Name: encode_to error, {:?}", err)))?;
387        Ok(())
388    }
389
390    pub fn from_bytes(buf: &[u8]) -> Result<Self, Error> {
391        if !buf.starts_with(&NS_PREFIX) {
392            return Err(Error::Custom("Name: invalid bytes".to_string()));
393        }
394
395        let name = Self::decode_from(buf)?;
396        let data = name.to_bytes()?;
397        if !buf.eq(&data) {
398            return Err(Error::Custom(
399                "Name: data not consumed entirely".to_string(),
400            ));
401        }
402        Ok(name)
403    }
404
405    pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
406        let mut buf: Vec<u8> = Vec::new();
407        self.encode_to(&mut buf)?;
408        Ok(buf)
409    }
410
411    pub fn to_sign_bytes(&self) -> Result<Vec<u8>, Error> {
412        let arr = Value::Array(vec![
413            Value::from(self.name.clone()),
414            Value::from(self.sequence),
415            Value::from(&self.service),
416        ]);
417        let mut buf: Vec<u8> = Vec::new();
418        into_writer(&arr, &mut buf).map_err(|err| Error::Custom(err.to_string()))?;
419        Ok(buf)
420    }
421}
422
423impl Name {
424    // validate the name is well-formed
425    pub fn validate(&self) -> Result<(), Error> {
426        if !valid_name(&self.name) {
427            return Err(Error::Custom(format!("Name: invalid name {}", self.name)));
428        }
429
430        if self.sequence > i64::MAX as u64 {
431            return Err(Error::Custom(format!(
432                "Name: invalid sequence {}, expected less than {}",
433                self.sequence,
434                i64::MAX
435            )));
436        }
437
438        if self.service.code > i64::MAX as u64 {
439            return Err(Error::Custom(format!(
440                "Name: invalid service code {}, expected less than {}",
441                self.service.code,
442                i64::MAX
443            )));
444        }
445
446        if let Some(attesters) = &self.service.attesters {
447            if attesters.is_empty() {
448                return Err(Error::Custom("Name: empty attesters".to_string()));
449            }
450            for attester in attesters {
451                if !valid_name(attester) {
452                    return Err(Error::Custom(format!(
453                        "Name: invalid attester {}",
454                        attester
455                    )));
456                }
457            }
458        }
459
460        if self.service.operations.is_empty() {
461            return Err(Error::Custom("Name: missing operations".to_string()));
462        }
463
464        if self.signatures.is_empty() {
465            return Err(Error::Custom("Name: missing signatures".to_string()));
466        }
467
468        let mut signatures = self.signatures.clone();
469        signatures.dedup();
470        if signatures.len() != self.signatures.len() {
471            return Err(Error::Custom("Name: duplicate signatures".to_string()));
472        }
473        Ok(())
474    }
475
476    // verify the data is signed by the public keys with the given threshold level
477    pub fn verify(&self, params: &PublicKeyParams, level: ThresholdLevel) -> Result<(), Error> {
478        let threshold = params.verifying_threshold(level);
479        if threshold == 0 {
480            return Err(Error::Custom(
481                "Name: threshold must be greater than 0".to_string(),
482            ));
483        }
484
485        let data = self.to_sign_bytes()?;
486        let mut keys: Vec<ed25519::VerifyingKey> = Vec::with_capacity(params.public_keys.len());
487        for pk in &params.public_keys {
488            let key = ed25519::VerifyingKey::from_bytes(&pk.0)
489                .map_err(|err| Error::Custom(err.to_string()))?;
490            keys.push(key);
491        }
492
493        let mut count = 0;
494        for sig in self.signatures.iter() {
495            let sig = ed25519::Signature::from_bytes(&sig.0);
496            for key in keys.iter() {
497                if key.verify_strict(&data, &sig).is_ok() {
498                    count += 1;
499                    if count >= threshold {
500                        return Ok(());
501                    }
502
503                    break;
504                }
505            }
506        }
507
508        Err(Error::Custom(format!(
509            "Name: verify failed, expected {} signatures, got {}",
510            threshold, count
511        )))
512    }
513
514    pub fn sign(
515        &mut self,
516        params: &PublicKeyParams,
517        level: ThresholdLevel,
518        signers: &[ed25519::SigningKey],
519    ) -> Result<(), Error> {
520        let threshold = params.verifying_threshold(level);
521        if threshold == 0 {
522            return Err(Error::Custom(
523                "Name: threshold must be greater than 0".to_string(),
524            ));
525        }
526
527        let data = self.to_sign_bytes()?;
528        self.signatures = Vec::with_capacity(threshold as usize);
529        // siging in order of public keys
530        for pk in params.public_keys.iter() {
531            if let Some(signer) = signers
532                .iter()
533                .find(|sk| sk.verifying_key().as_bytes() == &pk.0)
534            {
535                let sig = Bytes64::from(signer.sign(&data).to_bytes());
536                self.signatures.push(sig);
537                if self.signatures.len() == threshold as usize {
538                    break;
539                }
540            }
541        }
542
543        if self.signatures.len() != threshold as usize {
544            return Err(Error::Custom(format!(
545                "Name: expected {} signatures, got {}",
546                threshold,
547                self.signatures.len()
548            )));
549        }
550
551        Ok(())
552    }
553
554    pub fn sign_with(&mut self, signer: &ed25519::SigningKey) -> Result<(), Error> {
555        let data = self.to_sign_bytes()?;
556        let sig = Bytes64::from(signer.sign(&data).to_bytes());
557        self.signatures.push(sig);
558        Ok(())
559    }
560}
561
562impl From<&Bytes32> for Value {
563    fn from(val: &Bytes32) -> Self {
564        Value::Bytes(val.to_vec())
565    }
566}
567
568impl From<&Bytes64> for Value {
569    fn from(val: &Bytes64) -> Self {
570        Value::Bytes(val.to_vec())
571    }
572}
573
574impl From<&PublicKeyParams> for Value {
575    fn from(params: &PublicKeyParams) -> Self {
576        let mut arr = vec![Value::Array(
577            params.public_keys.iter().map(Value::from).collect(),
578        )];
579        if let Some(threshold) = params.threshold {
580            arr.push(Value::Integer(threshold.into()));
581        }
582        if let Some(kind) = params.kind {
583            if params.threshold.is_none() {
584                arr.push(Value::Integer(params.public_keys.len().into()));
585            }
586            arr.push(Value::Integer(kind.into()));
587        }
588        Value::Array(arr)
589    }
590}
591
592impl From<&Operation> for Value {
593    fn from(op: &Operation) -> Self {
594        Value::Array(vec![op.subcode.into(), op.params.clone()])
595    }
596}
597
598impl From<&Service> for Value {
599    fn from(service: &Service) -> Self {
600        let mut arr = vec![
601            service.code.into(),
602            Value::Array(service.operations.iter().map(Value::from).collect()),
603        ];
604        if let Some(attesters) = &service.attesters {
605            arr.push(Value::Array(
606                attesters.clone().into_iter().map(Value::from).collect(),
607            ));
608        }
609        Value::Array(arr)
610    }
611}
612
613impl From<&Name> for Value {
614    fn from(name: &Name) -> Self {
615        Value::Array(vec![
616            Value::from(name.name.clone()),
617            Value::from(name.sequence),
618            Value::from(&name.service),
619            Value::Array(name.signatures.iter().map(Value::from).collect()),
620        ])
621    }
622}
623
624impl TryFrom<&Value> for Bytes32 {
625    type Error = Error;
626
627    fn try_from(value: &Value) -> Result<Self, Self::Error> {
628        match value {
629            Value::Bytes(bytes) => Bytes32::try_from(bytes),
630            _ => Err(Error::Custom(format!(
631                "Bytes32: expected bytes, got {}",
632                kind_of_value(value)
633            ))),
634        }
635    }
636}
637
638impl TryFrom<&Value> for Bytes64 {
639    type Error = Error;
640
641    fn try_from(value: &Value) -> Result<Self, Self::Error> {
642        match value {
643            Value::Bytes(bytes) => Bytes64::try_from(bytes),
644            _ => Err(Error::Custom(format!(
645                "Bytes64: expected bytes, got {}",
646                kind_of_value(value)
647            ))),
648        }
649    }
650}
651
652impl TryFrom<&Value> for Operation {
653    type Error = Error;
654    fn try_from(value: &Value) -> Result<Self, Self::Error> {
655        match value {
656            Value::Array(arr) => {
657                if arr.len() != 2 {
658                    return Err(Error::Custom(format!(
659                        "Operation: expected array of length is 2, got {:?}",
660                        arr.len()
661                    )));
662                }
663
664                Ok(Operation {
665                    subcode: u16::try_from(&IntValue(&arr[0]))?,
666                    params: arr[1].clone(),
667                })
668            }
669            _ => Err(Error::Custom(format!(
670                "Operation: expected array, got {}",
671                kind_of_value(value)
672            ))),
673        }
674    }
675}
676
677impl TryFrom<&Value> for Service {
678    type Error = Error;
679    fn try_from(value: &Value) -> Result<Self, Self::Error> {
680        let arr = value.as_array().ok_or_else(|| {
681            Error::Custom(format!(
682                "Service: expected array, got {}",
683                kind_of_value(value)
684            ))
685        })?;
686        match arr.len() {
687            v if v == 2 || v == 3 => {
688                let mut srv = Service {
689                    code: u64::try_from(&IntValue(&arr[0]))?,
690                    operations: arr[1]
691                        .as_array()
692                        .ok_or_else(|| {
693                            Error::Custom(format!(
694                                "Service: expected array, got {}",
695                                kind_of_value(&arr[1])
696                            ))
697                        })?
698                        .iter()
699                        .map(Operation::try_from)
700                        .collect::<Result<Vec<Operation>, Self::Error>>()?,
701                    attesters: None,
702                };
703                if v == 3 {
704                    let attesters = arr[2].as_array().ok_or_else(|| {
705                        Error::Custom(format!(
706                            "Service: expected array, got {}",
707                            kind_of_value(&arr[2])
708                        ))
709                    })?;
710                    if attesters.is_empty() {
711                        return Err(Error::Custom(
712                            "Service: expected non-empty array of attesters".to_string(),
713                        ));
714                    }
715
716                    let attesters: Result<Vec<String>, Error> = attesters
717                        .iter()
718                        .map(|v| {
719                            v.as_text().map(String::from).ok_or_else(|| {
720                                Error::Custom(format!(
721                                    "Name: expected text, got {}",
722                                    kind_of_value(&arr[0])
723                                ))
724                            })
725                        })
726                        .collect();
727                    srv.attesters = Some(attesters?);
728                }
729                Ok(srv)
730            }
731            v => Err(Error::Custom(format!(
732                "Service: expected array of length 2 or 3, got {}",
733                v
734            ))),
735        }
736    }
737}
738
739impl TryFrom<&Value> for PublicKeyParams {
740    type Error = Error;
741    fn try_from(value: &Value) -> Result<Self, Self::Error> {
742        let arr = value.as_array().ok_or_else(|| {
743            Error::Custom(format!(
744                "PublicKeyParams: expected array, got {}",
745                kind_of_value(value)
746            ))
747        })?;
748        match arr.len() {
749            v if (1..=3).contains(&v) => {
750                let mut params = PublicKeyParams {
751                    public_keys: Bytes32::vec_try_from_value(&arr[0])?,
752                    threshold: None,
753                    kind: None,
754                };
755                if v >= 2 {
756                    let threshold = u8::try_from(&IntValue(&arr[1]))?;
757                    params.threshold = Some(threshold);
758                }
759
760                if v == 3 {
761                    let kind = u8::try_from(&IntValue(&arr[2]))?;
762                    params.kind = Some(kind);
763                }
764                Ok(params)
765            }
766            v => Err(Error::Custom(format!(
767                "PublicKeyParams: expected array of length [1, 3], got {}",
768                v
769            ))),
770        }
771    }
772}
773
774impl TryFrom<&Value> for Name {
775    type Error = Error;
776    fn try_from(value: &Value) -> Result<Self, Self::Error> {
777        let arr = value.as_array().ok_or_else(|| {
778            Error::Custom(format!(
779                "Name: expected array, got {}",
780                kind_of_value(value)
781            ))
782        })?;
783        match arr.len() {
784            4 => Ok(Name {
785                name: arr[0]
786                    .as_text()
787                    .ok_or_else(|| {
788                        Error::Custom(format!(
789                            "Name: expected text, got {}",
790                            kind_of_value(&arr[0])
791                        ))
792                    })?
793                    .to_string(),
794                sequence: u64::try_from(&IntValue(&arr[1]))?,
795                service: Service::try_from(&arr[2])?,
796                signatures: Bytes64::vec_try_from_value(&arr[3])?,
797            }),
798            _ => Err(Error::Custom(format!(
799                "Name: expected array of length 4, got {}",
800                arr.len()
801            ))),
802        }
803    }
804}
805
806impl Serialize for Bytes32 {
807    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
808    where
809        S: ser::Serializer,
810    {
811        serializer.serialize_bytes(&self.0)
812    }
813}
814
815impl<'de> Deserialize<'de> for Bytes32 {
816    fn deserialize<D>(deserializer: D) -> Result<Bytes32, D::Error>
817    where
818        D: de::Deserializer<'de>,
819    {
820        let val = Value::deserialize(deserializer)?;
821        Bytes32::try_from(&val).map_err(de::Error::custom)
822    }
823}
824
825impl Serialize for Bytes64 {
826    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
827    where
828        S: ser::Serializer,
829    {
830        serializer.serialize_bytes(&self.0)
831    }
832}
833
834impl<'de> Deserialize<'de> for Bytes64 {
835    fn deserialize<D>(deserializer: D) -> Result<Bytes64, D::Error>
836    where
837        D: de::Deserializer<'de>,
838    {
839        let val = Value::deserialize(deserializer)?;
840        Bytes64::try_from(&val).map_err(de::Error::custom)
841    }
842}
843
844impl Serialize for PublicKeyParams {
845    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
846    where
847        S: ser::Serializer,
848    {
849        Value::from(self).serialize(serializer)
850    }
851}
852
853impl<'de> Deserialize<'de> for PublicKeyParams {
854    fn deserialize<D>(deserializer: D) -> Result<PublicKeyParams, D::Error>
855    where
856        D: de::Deserializer<'de>,
857    {
858        let val = Value::deserialize(deserializer)?;
859        PublicKeyParams::try_from(&val).map_err(de::Error::custom)
860    }
861}
862
863impl Serialize for Service {
864    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
865    where
866        S: ser::Serializer,
867    {
868        Value::from(self).serialize(serializer)
869    }
870}
871
872impl<'de> Deserialize<'de> for Service {
873    fn deserialize<D>(deserializer: D) -> Result<Service, D::Error>
874    where
875        D: de::Deserializer<'de>,
876    {
877        let val = Value::deserialize(deserializer)?;
878        Service::try_from(&val).map_err(de::Error::custom)
879    }
880}
881
882impl Serialize for Name {
883    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
884    where
885        S: ser::Serializer,
886    {
887        Value::from(self).serialize(serializer)
888    }
889}
890
891impl<'de> Deserialize<'de> for Name {
892    fn deserialize<D>(deserializer: D) -> Result<Name, D::Error>
893    where
894        D: de::Deserializer<'de>,
895    {
896        let val = Value::deserialize(deserializer)?;
897        Name::try_from(&val).map_err(de::Error::custom)
898    }
899}
900
901pub(crate) fn kind_of_value(v: &Value) -> String {
902    match v {
903        Value::Integer(_) => "integer".to_string(),
904        Value::Bytes(_) => "bytes".to_string(),
905        Value::Text(_) => "text".to_string(),
906        Value::Array(_) => "array".to_string(),
907        Value::Map(_) => "map".to_string(),
908        Value::Tag(_, _) => "tag".to_string(),
909        Value::Bool(_) => "bool".to_string(),
910        Value::Null => "null".to_string(),
911        Value::Float(_) => "float".to_string(),
912        _ => "unknown".to_string(),
913    }
914}
915
916#[cfg(test)]
917mod tests {
918    use super::*;
919    use hex_literal::hex;
920    use rand_core::{OsRng, RngCore};
921
922    fn secret_key() -> [u8; 32] {
923        let mut data = [0u8; 32];
924        OsRng.fill_bytes(&mut data);
925        data
926    }
927
928    #[test]
929    fn valid_name_works() {
930        for name in &["a", "abc", "ʦ", "公信", "0", "b0"] {
931            assert!(valid_name(name), "{} is invalid", name)
932        }
933        for name in &[
934            "",
935            " ",
936            "‍",
937            "\n",
938            "a‍",
939            "A",
940            ".",
941            ":",
942            "*",
943            "。",
944            "-",
945            "_",
946            "——",
947            "\0",
948            "\u{301}",
949            "🀄",
950            "❤️‍🔥",
951            "a\u{301}",
952        ] {
953            assert!(!valid_name(name), "{} is valid", name)
954        }
955    }
956
957    #[test]
958    fn check_ascii_name() {
959        let mut i = 0;
960        let mut result: String = String::new();
961        while i < 127 {
962            let s = char::from(i).to_string();
963            // println!("{}>{}<: {}", i, s, valid_name(&s));
964            if valid_name(&s) {
965                result.push_str(&s)
966            }
967            i += 1;
968        }
969        assert_eq!(result, "0123456789abcdefghijklmnopqrstuvwxyz");
970    }
971
972    #[test]
973    fn check_greek_name() {
974        for name in &[
975            "α", "β", "γ", "δ", "ε", "ζ", "η", "θ", "ι", "κ", "λ", "μ", "ν", "ξ", "ο", "π", "ρ",
976            "ς", "σ", "τ", "υ", "φ", "χ", "ψ", "ω", "ϕ", "ϵ",
977        ] {
978            println!("{} is {}", name, valid_name(name))
979        }
980    }
981
982    #[test]
983    fn signature_ser_de() {
984        let sig = Bytes64(hex!("6b71fd0c8ae2ccc910c39dd20e76653fccca2638b7935f2312e954f5dccd71b209c58ca57e9d4fc2d3c06a57d585dbadf4535abb8a9cf103eeb9b9717d87f201"));
985        let mut buf: Vec<u8> = Vec::new();
986        into_writer(&sig, &mut buf).unwrap();
987        assert_eq!(buf.len(), 66);
988        assert_eq!(buf[0], 0x58); // byte string
989        assert_eq!(buf[1], 0x40); // 64 bytes
990        let sig2: Bytes64 = from_reader(&buf[..]).unwrap();
991        assert_eq!(sig, sig2);
992    }
993
994    #[test]
995    fn name_ser_de() {
996        let secret_key = Bytes32(hex!(
997            "7ef3811aabb916dc2f646ef1a371b90adec91bc07992cd4d44c156c42fc1b300"
998        ));
999        let public_key = Bytes32(hex!(
1000            "ee90735ac719e85dc2f3e5974036387fdf478af7d9d1f8480e97eee601890266"
1001        ));
1002        let params = PublicKeyParams {
1003            public_keys: vec![public_key],
1004            threshold: Some(1),
1005            kind: None,
1006        };
1007        let signer = ed25519::SigningKey::from_bytes(&secret_key.0);
1008        assert!(params.validate().is_ok());
1009
1010        let mut name = Name {
1011            name: "a".to_string(),
1012            sequence: 0,
1013            service: Service {
1014                code: 0,
1015                operations: vec![Operation {
1016                    subcode: 1,
1017                    params: Value::from(&params),
1018                }],
1019                attesters: None,
1020            },
1021            signatures: vec![],
1022        };
1023        assert!(name.validate().is_err());
1024        name.sign(&params, ThresholdLevel::Default, &[signer])
1025            .unwrap();
1026        assert!(name.validate().is_ok());
1027        assert!(name.verify(&params, ThresholdLevel::Single).is_ok());
1028        assert!(name.verify(&params, ThresholdLevel::Default).is_ok());
1029        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1030        assert!(name.verify(&params, ThresholdLevel::All).is_ok());
1031        assert_eq!(name.signatures, vec![Bytes64(
1032            hex!("e23554d996647e86f69115d04515398cc7463062d2683b099371360e93fa1cba02351492b70ef31037baa7780053bcf20b12bafe9531ee17fe140b93082a3f0c")
1033        )]);
1034
1035        let data = name.to_bytes().unwrap();
1036        assert_eq!(hex::encode(&data), "d83584616100820081820182815820ee90735ac719e85dc2f3e5974036387fdf478af7d9d1f8480e97eee60189026601815840e23554d996647e86f69115d04515398cc7463062d2683b099371360e93fa1cba02351492b70ef31037baa7780053bcf20b12bafe9531ee17fe140b93082a3f0c");
1037        // 53(["a", 0, [0, [[1, [[h'ee90735ac719e85dc2f3e5974036387fdf478af7d9d1f8480e97eee601890266'], 1]]]], [h'e23554d996647e86f69115d04515398cc7463062d2683b099371360e93fa1cba02351492b70ef31037baa7780053bcf20b12bafe9531ee17fe140b93082a3f0c']])
1038
1039        let name2 = Name::decode_from(&data[..]).unwrap();
1040        assert_eq!(name, name2);
1041        assert_eq!(name2.to_bytes().unwrap(), data);
1042
1043        let name3 = Name::from_bytes(&data[..]).unwrap();
1044        assert_eq!(name, name3);
1045        assert_eq!(name3.to_bytes().unwrap(), data);
1046
1047        let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 1);
1048        buf.extend_from_slice(&data);
1049        buf.push(0x80);
1050        assert!(Name::from_bytes(&buf[..]).is_err());
1051    }
1052
1053    #[test]
1054    fn name_sign_verify() {
1055        let s1 = ed25519::SigningKey::from_bytes(&secret_key());
1056        let s2 = ed25519::SigningKey::from_bytes(&secret_key());
1057        let s3 = ed25519::SigningKey::from_bytes(&secret_key());
1058        let s4 = ed25519::SigningKey::from_bytes(&secret_key());
1059        let mut signers = vec![s1.clone(), s2.clone(), s3.clone(), s4.clone()];
1060
1061        let params = PublicKeyParams {
1062            public_keys: vec![
1063                s1.verifying_key().as_bytes().into(),
1064                s2.verifying_key().as_bytes().into(),
1065                s3.verifying_key().as_bytes().into(),
1066                s4.verifying_key().as_bytes().into(),
1067            ],
1068            threshold: Some(2),
1069            kind: None,
1070        };
1071
1072        let mut name = Name {
1073            name: "道".to_string(),
1074            sequence: 0,
1075            service: Service {
1076                code: 0,
1077                operations: vec![Operation {
1078                    subcode: 1,
1079                    params: Value::from(&params),
1080                }],
1081                attesters: None,
1082            },
1083            signatures: vec![],
1084        };
1085        assert!(name.validate().is_err());
1086        name.sign(&params, ThresholdLevel::Single, &signers)
1087            .unwrap();
1088        assert!(name.validate().is_ok());
1089        assert_eq!(1, name.signatures.len());
1090        assert!(name.verify(&params, ThresholdLevel::Single).is_ok());
1091        assert!(name.verify(&params, ThresholdLevel::Default).is_err());
1092        assert!(name.verify(&params, ThresholdLevel::Strict).is_err());
1093        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1094
1095        let mut invalid_name = name.clone();
1096        invalid_name.sequence = 1;
1097        assert!(invalid_name
1098            .verify(&params, ThresholdLevel::Single)
1099            .is_err());
1100
1101        name.sign(&params, ThresholdLevel::Default, &signers)
1102            .unwrap();
1103        assert!(name.validate().is_ok());
1104        assert_eq!(2, name.signatures.len());
1105        assert!(name.verify(&params, ThresholdLevel::Single).is_ok());
1106        assert!(name.verify(&params, ThresholdLevel::Default).is_ok());
1107        assert!(name.verify(&params, ThresholdLevel::Strict).is_err());
1108        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1109
1110        name.sign(&params, ThresholdLevel::Strict, &signers)
1111            .unwrap();
1112        assert!(name.validate().is_ok());
1113        assert_eq!(3, name.signatures.len());
1114        assert!(name.verify(&params, ThresholdLevel::Single).is_ok());
1115        assert!(name.verify(&params, ThresholdLevel::Default).is_ok());
1116        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1117        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1118
1119        name.sign(&params, ThresholdLevel::All, &signers).unwrap();
1120        assert!(name.validate().is_ok());
1121        assert_eq!(4, name.signatures.len());
1122        assert!(name.verify(&params, ThresholdLevel::Single).is_ok());
1123        assert!(name.verify(&params, ThresholdLevel::Default).is_ok());
1124        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1125        assert!(name.verify(&params, ThresholdLevel::All).is_ok());
1126
1127        assert!(
1128            name.sign(&params, ThresholdLevel::All, &signers[1..])
1129                .is_err(),
1130            "signers less than ThresholdLevel::All"
1131        );
1132        assert!(name
1133            .sign(&params, ThresholdLevel::Strict, &signers[1..])
1134            .is_ok());
1135        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1136        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1137
1138        signers[3] = s3.clone();
1139        assert!(
1140            name.sign(&params, ThresholdLevel::All, &signers).is_err(),
1141            "depulicate signer"
1142        );
1143        assert!(name.sign(&params, ThresholdLevel::Strict, &signers).is_ok());
1144        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1145        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1146
1147        signers[3] = ed25519::SigningKey::from_bytes(&secret_key());
1148        assert!(
1149            name.sign(&params, ThresholdLevel::All, &signers).is_err(),
1150            "stranger signer"
1151        );
1152        assert!(name.sign(&params, ThresholdLevel::Strict, &signers).is_ok());
1153        assert!(name.verify(&params, ThresholdLevel::Strict).is_ok());
1154        assert!(name.verify(&params, ThresholdLevel::All).is_err());
1155
1156        signers[3] = s4.clone();
1157        assert!(name.sign(&params, ThresholdLevel::All, &signers).is_ok());
1158        assert!(name.verify(&params, ThresholdLevel::All).is_ok());
1159    }
1160}