|
| 1 | +//! Signature domain models. |
| 2 | +
|
| 3 | +use std::borrow::Cow; |
| 4 | + |
| 5 | +use ed25519_dalek::Signer; |
| 6 | +use tl_proto::{TlRead, TlWrite}; |
| 7 | + |
| 8 | +/// Signature domain variants. |
| 9 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TlRead, TlWrite)] |
| 10 | +#[tl( |
| 11 | + boxed, |
| 12 | + scheme_inline = r#" |
| 13 | + signature_domain.l2#71b34ee1 global_id:int = SignatureDomain; |
| 14 | + signature_domain.empty#e1d571b = SignatureDomain; |
| 15 | + "# |
| 16 | +)] |
| 17 | +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] |
| 18 | +#[cfg_attr(feature = "serde", serde(tag = "type", content = "id"))] |
| 19 | +pub enum SignatureDomain { |
| 20 | + /// Special variant to NOT add any prefix for the verified data. |
| 21 | + /// Can be used to verify mainnet signatures from L2 networks. |
| 22 | + #[tl(id = "signature_domain.empty")] |
| 23 | + Empty, |
| 24 | + /// Non-empty variant. Hash of its TL representation |
| 25 | + /// is used as a prefix for the verified data. |
| 26 | + #[tl(id = "signature_domain.l2")] |
| 27 | + L2 { |
| 28 | + /// Global id of the network. |
| 29 | + global_id: i32, |
| 30 | + }, |
| 31 | +} |
| 32 | + |
| 33 | +impl SignatureDomain { |
| 34 | + /// Signs arbitrary data using the key and optional signature id. |
| 35 | + pub fn sign(&self, key: &ed25519_dalek::SigningKey, data: &[u8]) -> ed25519_dalek::Signature { |
| 36 | + let data = self.apply(data); |
| 37 | + key.sign(&data) |
| 38 | + } |
| 39 | + |
| 40 | + /// Prepares arbitrary data for signing. |
| 41 | + pub fn apply<'a>(&self, data: &'a [u8]) -> Cow<'a, [u8]> { |
| 42 | + if let Self::Empty = self { |
| 43 | + Cow::Borrowed(data) |
| 44 | + } else { |
| 45 | + let hash = tl_proto::hash(self); |
| 46 | + |
| 47 | + let mut result = Vec::with_capacity(32 + data.len()); |
| 48 | + result.extend_from_slice(&hash); |
| 49 | + result.extend_from_slice(data); |
| 50 | + Cow::Owned(result) |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments