Skip to main content

soroban_cli/commands/message/
verify.rs

1use std::io::{self, Read};
2
3use crate::{
4    commands::global,
5    config::{locator, secret},
6    print::Print,
7};
8use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
9use clap::Parser;
10use ed25519_dalek::{Signature, Verifier, VerifyingKey};
11use sha2::{Digest, Sha256};
12
13use super::SEP53_PREFIX;
14
15#[derive(thiserror::Error, Debug)]
16pub enum Error {
17    #[error(transparent)]
18    Locator(#[from] locator::Error),
19
20    #[error(transparent)]
21    Secret(#[from] secret::Error),
22
23    #[error(transparent)]
24    Io(#[from] io::Error),
25
26    #[error(transparent)]
27    Base64(#[from] base64::DecodeError),
28
29    #[error(transparent)]
30    StrKey(#[from] stellar_strkey::DecodeError),
31
32    #[error(transparent)]
33    Ed25519(#[from] ed25519_dalek::SignatureError),
34
35    #[error(transparent)]
36    Address(#[from] crate::config::address::Error),
37
38    #[error("Signature verification failed")]
39    VerificationFailed,
40
41    #[error("Invalid signature length: expected 64 bytes, got {0}")]
42    InvalidSignatureLength(usize),
43}
44
45#[derive(Debug, Parser, Clone)]
46#[group(skip)]
47pub struct Cmd {
48    /// The message to verify. If not provided, reads from stdin. This should **not** include
49    /// the SEP-53 prefix "Stellar Signed Message:\n", as it will be added automatically.
50    #[arg()]
51    pub message: Option<String>,
52
53    /// Treat the message as base64-encoded binary data
54    #[arg(long)]
55    pub base64: bool,
56
57    /// The base64-encoded signature to verify
58    #[arg(long, short = 's')]
59    pub signature: String,
60
61    /// The public key to verify the signature against. Can be an identity (--public-key alice),
62    /// a public key (--public-key GDKW...).
63    #[arg(long, short = 'p')]
64    pub public_key: String,
65
66    /// If public key identity is a seed phrase use this hd path, default is 0
67    #[arg(long)]
68    pub hd_path: Option<usize>,
69
70    #[command(flatten)]
71    pub locator: locator::Args,
72}
73
74impl Cmd {
75    pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
76        let print = Print::new(global_args.quiet);
77
78        // Create the SEP-53 payload: prefix + message as utf-8 byte array
79        let message_bytes = self.get_message_bytes()?;
80        let mut payload = Vec::with_capacity(SEP53_PREFIX.len() + message_bytes.len());
81        payload.extend_from_slice(SEP53_PREFIX.as_bytes());
82        payload.extend_from_slice(&message_bytes);
83
84        // Hash the payload with SHA-256
85        let hash: [u8; 32] = Sha256::digest(&payload).into();
86
87        // Decode the signature
88        let signature_bytes = BASE64.decode(&self.signature)?;
89        if signature_bytes.len() != 64 {
90            return Err(Error::InvalidSignatureLength(signature_bytes.len()));
91        }
92        let signature = Signature::from_slice(&signature_bytes)?;
93
94        // Get the verifying key
95        let public_key = self.get_public_key()?;
96        print.infoln(format!("Verifying signature against: {public_key}"));
97        let verifying_key = VerifyingKey::from_bytes(&public_key.0)?;
98
99        // Verify the signature
100        if verifying_key.verify(&hash, &signature).is_ok() {
101            print.checkln("Signature valid");
102            Ok(())
103        } else {
104            print.errorln("Signature invalid");
105            Err(Error::VerificationFailed)
106        }
107    }
108
109    fn get_message_bytes(&self) -> Result<Vec<u8>, Error> {
110        let message_str = if let Some(msg) = &self.message {
111            msg.clone()
112        } else {
113            // Read from stdin
114            let mut buffer = String::new();
115            io::stdin().read_to_string(&mut buffer)?;
116            // Remove trailing newline if present
117            if buffer.ends_with('\n') {
118                buffer.pop();
119                if buffer.ends_with('\r') {
120                    buffer.pop();
121                }
122            }
123            buffer
124        };
125
126        if self.base64 {
127            // Decode base64 input
128            Ok(BASE64.decode(&message_str)?)
129        } else {
130            // Use UTF-8 encoded message
131            Ok(message_str.into_bytes())
132        }
133    }
134
135    fn get_public_key(&self) -> Result<stellar_strkey::ed25519::PublicKey, Error> {
136        // try to parse as stellar public key first
137        if let Ok(pk) = stellar_strkey::ed25519::PublicKey::from_string(&self.public_key) {
138            return Ok(pk);
139        }
140
141        // otherwise treat as identity and resolve
142        let account = self
143            .locator
144            .read_key(&self.public_key)?
145            .muxed_account(self.hd_path)
146            .map_err(crate::config::address::Error::from)?;
147        let bytes = match account {
148            soroban_sdk::xdr::MuxedAccount::Ed25519(uint256) => uint256.0,
149            soroban_sdk::xdr::MuxedAccount::MuxedEd25519(muxed_account) => muxed_account.ed25519.0,
150        };
151        Ok(stellar_strkey::ed25519::PublicKey(bytes))
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    // Public key = GBXFXNDLV4LSWA4VB7YIL5GBD7BVNR22SGBTDKMO2SBZZHDXSKZYCP7L
160    const TEST_PUBLIC_KEY: &str = "GBXFXNDLV4LSWA4VB7YIL5GBD7BVNR22SGBTDKMO2SBZZHDXSKZYCP7L";
161    const FALSE_PUBLIC_KEY: &str = "GAREAZZQWHOCBJS236KIE3AWYBVFLSBK7E5UW3ICI3TCRWQKT5LNLCEZ";
162    const FALSE_SIGNATURE: &str =
163        "+F//cUINZgTe4vZNXOEJTchDgEYlvy+iGFH3P65KeVhoyZgAsmGRRYAQLVqgY9J3PAlHPbSSeU5advhswmAfDg==";
164
165    fn setup_locator() -> locator::Args {
166        let temp_dir = tempfile::tempdir().unwrap();
167        locator::Args {
168            config_dir: Some(temp_dir.path().to_path_buf()),
169        }
170    }
171
172    fn global_args() -> global::Args {
173        global::Args {
174            quiet: true,
175            ..Default::default()
176        }
177    }
178
179    #[test]
180    fn test_verify_simple() {
181        // SEP-53 - test case 1
182        let message = "Hello, World!".to_string();
183        let signature = "fO5dbYhXUhBMhe6kId/cuVq/AfEnHRHEvsP8vXh03M1uLpi5e46yO2Q8rEBzu3feXQewcQE5GArp88u6ePK6BA==";
184
185        let global = global_args();
186        let locator = setup_locator();
187        let cmd = super::Cmd {
188            message: Some(message),
189            base64: false,
190            signature: signature.to_string(),
191            public_key: TEST_PUBLIC_KEY.to_string(),
192            hd_path: None,
193            locator: locator.clone(),
194        };
195        let successful = cmd.run(&global);
196        assert!(successful.is_ok());
197    }
198
199    #[test]
200    fn test_verify_japanese() {
201        // SEP-53 - test case 2
202        let message = "こんにちは、世界!".to_string();
203        let signature = "CDU265Xs8y3OWbB/56H9jPgUss5G9A0qFuTqH2zs2YDgTm+++dIfmAEceFqB7bhfN3am59lCtDXrCtwH2k1GBA==";
204
205        let global = global_args();
206        let locator = setup_locator();
207        let cmd = super::Cmd {
208            message: Some(message),
209            base64: false,
210            signature: signature.to_string(),
211            public_key: TEST_PUBLIC_KEY.to_string(),
212            hd_path: None,
213            locator: locator.clone(),
214        };
215        let successful = cmd.run(&global);
216        assert!(successful.is_ok());
217    }
218
219    #[test]
220    fn test_verify_base64() {
221        // SEP-53 - test case 3
222        let message = "2zZDP1sa1BVBfLP7TeeMk3sUbaxAkUhBhDiNdrksaFo=".to_string();
223        let signature = "VA1+7hefNwv2NKScH6n+Sljj15kLAge+M2wE7fzFOf+L0MMbssA1mwfJZRyyrhBORQRle10X1Dxpx+UOI4EbDQ==";
224
225        let global = global_args();
226        let locator = setup_locator();
227        let cmd = super::Cmd {
228            message: Some(message),
229            base64: true,
230            signature: signature.to_string(),
231            public_key: TEST_PUBLIC_KEY.to_string(),
232            hd_path: None,
233            locator: locator.clone(),
234        };
235        let successful = cmd.run(&global);
236        assert!(successful.is_ok());
237    }
238
239    #[test]
240    fn test_verify_bad_signature_errors() {
241        let message = "Hello, World!".to_string();
242
243        let global = global_args();
244        let locator = setup_locator();
245        let cmd = super::Cmd {
246            message: Some(message),
247            base64: false,
248            signature: FALSE_SIGNATURE.to_string(),
249            public_key: TEST_PUBLIC_KEY.to_string(),
250            hd_path: None,
251            locator: locator.clone(),
252        };
253        let successful = cmd.run(&global);
254        assert!(successful.is_err());
255    }
256
257    #[test]
258    fn test_verify_bad_pubkey_errors() {
259        let message = "Hello, World!".to_string();
260        let signature = "fO5dbYhXUhBMhe6kId/cuVq/AfEnHRHEvsP8vXh03M1uLpi5e46yO2Q8rEBzu3feXQewcQE5GArp88u6ePK6BA==";
261
262        let global = global_args();
263        let locator = setup_locator();
264        let cmd = super::Cmd {
265            message: Some(message),
266            base64: false,
267            signature: signature.to_string(),
268            public_key: FALSE_PUBLIC_KEY.to_string(),
269            hd_path: None,
270            locator: locator.clone(),
271        };
272        let successful = cmd.run(&global);
273        assert!(successful.is_err());
274    }
275}