defuse_tip191/
lib.rs

1use defuse_crypto::{CryptoHash, Curve, Payload, Secp256k1, SignedPayload, serde::AsCurve};
2use impl_tools::autoimpl;
3use near_sdk::{env, near};
4use serde_with::serde_as;
5
6/// See [TIP-191](https://github.com/tronprotocol/tips/blob/master/tip-191.md)
7#[near(serializers = [json])]
8#[derive(Debug, Clone)]
9pub struct Tip191Payload(pub String);
10
11impl Tip191Payload {
12    #[inline]
13    pub fn prehash(&self) -> Vec<u8> {
14        let data = self.0.as_bytes();
15        [
16            // Prefix not specified in the standard. But from: https://tronweb.network/docu/docs/Sign%20and%20Verify%20Message/
17            format!("\x19TRON Signed Message:\n{}", data.len()).as_bytes(),
18            data,
19        ]
20        .concat()
21    }
22}
23
24impl Payload for Tip191Payload {
25    #[inline]
26    fn hash(&self) -> CryptoHash {
27        env::keccak256_array(self.prehash())
28    }
29}
30
31#[near(serializers = [json])]
32#[autoimpl(Deref using self.payload)]
33#[derive(Debug, Clone)]
34pub struct SignedTip191Payload {
35    pub payload: Tip191Payload,
36
37    /// There is no public key member because the public key can be recovered
38    /// via `ecrecover()` knowing the data and the signature
39    #[serde_as(as = "AsCurve<Secp256k1>")]
40    pub signature: <Secp256k1 as Curve>::Signature,
41}
42
43impl Payload for SignedTip191Payload {
44    #[inline]
45    fn hash(&self) -> CryptoHash {
46        self.payload.hash()
47    }
48}
49
50impl SignedPayload for SignedTip191Payload {
51    type PublicKey = <Secp256k1 as Curve>::PublicKey;
52
53    #[inline]
54    fn verify(&self) -> Option<Self::PublicKey> {
55        Secp256k1::verify(&self.signature, &self.payload.hash(), &())
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use hex_literal::hex;
63
64    const fn fix_v_in_signature(mut sig: [u8; 65]) -> [u8; 65] {
65        if *sig.last().unwrap() >= 27 {
66            // Ethereum only uses uncompressed keys, with corresponding value v=27/28
67            // https://bitcoin.stackexchange.com/a/38909/58790
68            *sig.last_mut().unwrap() -= 27;
69        }
70        sig
71    }
72
73    // NOTE: Public key can be derived using `ethers_signers` crate:
74    // let wallet = LocalWallet::from_str(
75    //     "a4b319a82adfc43584e4537fec97a80516e16673db382cd91eba97abbab8ca56",
76    // )?;
77    // let signing_key = wallet.signer();
78    // let verifying_key = signing_key.verifying_key();
79    // let public_key = verifying_key.to_encoded_point(false);
80    // // Notice that we skip the first byte, 0x04
81    // println!("Public key: 0x{}", hex::encode(public_key.as_bytes()[1..]));
82
83    const REFERENCE_MESSAGE: &str = "Hello, TRON!";
84    const INVALID_REFERENCE_MESSAGE: &str = "this is not TRON reference input message";
85    const REFERENCE_SIGNATURE: [u8; 65] = hex!(
86        "eea1651a60600ec4d9c45e8ae81da1a78377f789f0ac2019de66ad943459913015ef9256809ee0e6bb76e303a0b4802e475c1d26ade5d585292b80c9fe9cb10c1c"
87    );
88    const INVALID_REFERENCE_SIGNATURE: [u8; 65] = hex!(
89        "0000000011111111000000001110111110000000011111111e66ad943459913015ef9256809ee0e6bb76e303a0b4802e475c1d26ade5d585292b80c9fe9cb10c1c"
90    );
91    const REFERENCE_PUBKEY: [u8; 64] = hex!(
92        "85a66984273f338ce4ef7b85e5430b008307e8591bb7c1b980852cf6423770b801f41e9438155eb53a5e20f748640093bb42ae3aeca035f7b7fd7a1a21f22f68"
93    );
94
95    #[test]
96    fn test_reference_signature_verification_works() {
97        assert_eq!(
98            SignedTip191Payload {
99                payload: Tip191Payload(REFERENCE_MESSAGE.to_string()),
100                signature: fix_v_in_signature(REFERENCE_SIGNATURE),
101            }
102            .verify(),
103            Some(REFERENCE_PUBKEY)
104        );
105    }
106
107    #[test]
108    fn test_invalid_reference_message_verification_fails() {
109        assert_ne!(
110            SignedTip191Payload {
111                payload: Tip191Payload(INVALID_REFERENCE_MESSAGE.to_string()),
112                signature: fix_v_in_signature(REFERENCE_SIGNATURE),
113            }
114            .verify(),
115            Some(REFERENCE_PUBKEY)
116        );
117    }
118
119    #[test]
120    fn test_invalid_reference_signature_verification_fails() {
121        assert_ne!(
122            SignedTip191Payload {
123                payload: Tip191Payload(REFERENCE_MESSAGE.to_string()),
124                signature: fix_v_in_signature(INVALID_REFERENCE_SIGNATURE),
125            }
126            .verify(),
127            Some(REFERENCE_PUBKEY)
128        );
129    }
130}