near_api_types/signable_message.rs
1use borsh::{BorshDeserialize, BorshSerialize};
2
3/// Used to distinguish message types that are sign by account keys, to avoid an
4/// abuse of signed messages as something else.
5///
6/// This prefix must be at the first four bytes of a message body that is
7/// signed under this signature scheme.
8///
9/// The scheme is a draft introduced to avoid security issues with the
10/// implementation of meta transactions (NEP-366) but will eventually be
11/// standardized with NEP-461 that solves the problem more generally.
12#[derive(
13 Debug,
14 Clone,
15 Copy,
16 PartialEq,
17 Eq,
18 PartialOrd,
19 Ord,
20 Hash,
21 BorshDeserialize,
22 BorshSerialize,
23 serde::Serialize,
24 serde::Deserialize,
25)]
26pub struct MessageDiscriminant {
27 /// The unique prefix, serialized in little-endian by borsh.
28 discriminant: u32,
29}
30
31const MIN_ON_CHAIN_DISCRIMINANT: u32 = 1 << 30;
32const NEP_366_META_TRANSACTIONS: u32 = MIN_ON_CHAIN_DISCRIMINANT + 366;
33
34/// A wrapper around a message that should be signed using this scheme.
35///
36/// Only used for constructing a signature, not used to transmit messages. The
37/// discriminant prefix is implicit and should be known by the receiver based on
38/// the context in which the message is received.
39#[derive(BorshSerialize)]
40pub struct SignableMessage<'a, T> {
41 pub discriminant: MessageDiscriminant,
42 pub msg: &'a T,
43}
44
45impl<'a, T: BorshSerialize> SignableMessage<'a, T> {
46 pub fn new(msg: &'a T, ty: SignableMessageType) -> Self {
47 let discriminant = ty.into();
48 Self { discriminant, msg }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
53#[non_exhaustive]
54pub enum SignableMessageType {
55 /// A delegate action, intended for a relayer to included it in an action list of a transaction.
56 DelegateAction,
57}
58
59impl From<SignableMessageType> for MessageDiscriminant {
60 fn from(ty: SignableMessageType) -> Self {
61 // unwrapping here is ok, we know the constant NEP numbers used are in range
62 match ty {
63 SignableMessageType::DelegateAction => Self {
64 discriminant: NEP_366_META_TRANSACTIONS,
65 },
66 }
67 }
68}