| 4 | use serde::Deserialize; |
| 5 | use serde_json::{Value, json}; |
| 6 | use wallet_engine::*; |
| 7 | use zeroize::Zeroizing; |
| 8 |
| 9 | use crate::{GramWalletError, Result}; |
| 10 |
| 11 | fn invalid(message: impl Into<String>) -> GramWalletError { |
| 12 | GramWalletError::Protocol { |
| 13 | message: message.into(), |
| 14 | } |
| 15 | } |
| 16 |
| 17 | fn protocol<T, E: std::fmt::Display>( |
| 18 | operation: &str, |
| 19 | result: std::result::Result<T, E>, |
| 20 | ) -> Result<T> { |
| 21 | result.map_err(|error| invalid(format!("{operation}: {error}"))) |
| 22 | } |
| 23 |
| 24 | #[derive(Deserialize)] |
| 25 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 26 | struct Parameters { |
| 27 | dapp_client_id: String, |
| 28 | session_nonce: String, |
| 29 | wallet_public_key: String, |
| 30 | wallet_address: String, |
| 31 | #[serde(default)] |
| 32 | client_id: Option<String>, |
| 33 | #[serde(default)] |
| 34 | challenge: Option<String>, |
| 35 | #[serde(default)] |
| 36 | decrypt: Option<String>, |
| 37 | #[serde(default)] |
| 38 | encrypt: Option<Value>, |
| 39 | #[serde(default)] |
| 40 | account: bool, |
| 41 | #[serde(default)] |
| 42 | proof_domain: Option<String>, |
| 43 | #[serde(default)] |
| 44 | proof_payload: Option<String>, |
| 45 | #[serde(default)] |
| 46 | sign_data: Option<ton_connect_core::SignDataPayload>, |
| 47 | #[serde(default)] |
| 48 | sign_domain: Option<String>, |
| 49 | #[serde(default)] |
| 50 | timestamp: Option<u64>, |
| 51 | } |
| 52 |
| 53 | // An invocation can only read the already-authorized phrase. It cannot persist |
| 54 | // secrets, submit transactions, or modify a journal. |
| 55 | struct PhraseHost(Zeroizing<String>); |
| 56 |
| 57 | fn unavailable() -> ProtectedSecretHostError { |
| 58 | ProtectedSecretHostError::Failed { |
| 59 | kind: ProtectedSecretHostErrorKind::PolicyViolation, |
| 60 | diagnostic: "Unsupported adapter operation".to_owned(), |
| 61 | } |
| 62 | } |
| 63 |
| 64 | #[async_trait::async_trait] |
| 65 | impl WalletPlatformHost for PhraseHost { |
| 66 | async fn read_protected_secret( |
| 67 | &self, |
| 68 | request: ProtectedSecretRead, |
| 69 | ) -> std::result::Result<Vec<u8>, ProtectedSecretHostError> { |
| 70 | if !matches!( |
| 71 | request.reason, |
| 72 | SecretAccessReason::SignTonConnectProof |
| 73 | | SecretAccessReason::DeriveTonConnectSessionKey |
| 74 | | SecretAccessReason::SignTonConnectData |
| 75 | ) { |
| 76 | return Err(unavailable()); |
| 77 | } |
| 78 | Ok(self.0.as_bytes().to_vec()) |
| 79 | } |
| 80 | async fn store_protected_secret( |
| 81 | &self, |
| 82 | _: ProtectedSecretStore, |
| 83 | ) -> std::result::Result<(), ProtectedSecretHostError> { |
| 84 | Err(unavailable()) |
| 85 | } |
| 86 | async fn delete_protected_secret( |
| 87 | &self, |
| 88 | _: ProtectedSecretRef, |
| 89 | ) -> std::result::Result<(), ProtectedSecretHostError> { |
| 90 | Err(unavailable()) |
| 91 | } |
| 92 | async fn load_journal( |
| 93 | &self, |
| 94 | _: JournalKey, |
| 95 | ) -> std::result::Result<Option<JournalRecord>, JournalHostError> { |
| 96 | Ok(None) |
| 97 | } |
| 98 | async fn compare_exchange_journal( |
| 99 | &self, |
| 100 | _: JournalCompareExchange, |
| 101 | ) -> std::result::Result<JournalCompareExchangeResult, JournalHostError> { |
| 102 | Err(JournalHostError::Failed { |
| 103 | kind: JournalHostErrorKind::Unavailable, |
| 104 | diagnostic: "No adapter journal".to_owned(), |
| 105 | }) |
| 106 | } |
| 107 | } |
| 108 |
| 109 | struct Session { |
| 110 | derived: Arc<TonConnectDerivedSession>, |
| 111 | lifecycle: Arc<WalletLifecycle>, |
| 112 | descriptor: WalletDescriptor, |
| 113 | } |
| 114 |
| 115 | impl Session { |
| 116 | fn new(phrase: String, p: &Parameters) -> Result<Self> { |
| 117 | let phrase = Zeroizing::new(phrase); |
| 118 | let normalized = Zeroizing::new( |
| 119 | phrase |
| 120 | .split_whitespace() |
| 121 | .map(str::to_lowercase) |
| 122 | .collect::<Vec<_>>() |
| 123 | .join(" "), |
| 124 | ); |
| 125 | // The descriptor uses the immutable anchor; the derived session below |
| 126 | // exposes the current signing key separately for the MTProto key check. |
| 127 | let anchor = rotation_mnemonic_public_key(normalized.to_string()) |
| 128 | .map_err(|_| invalid("Invalid wallet recovery phrase"))?; |
| 129 | let lifecycle = WalletLifecycle::new(Arc::new(PhraseHost(normalized))); |
| 130 | // Gram Wallet currently uses mainnet, as does the Android WalletClient. |
| 131 | let descriptor = WalletDescriptor { |
| 132 | record_id: "ton-connect".to_owned(), |
| 133 | address: protocol( |
| 134 | "Parse wallet address", |
| 135 | TonAddressString::try_from(p.wallet_address.clone()), |
| 136 | )?, |
| 137 | public_key: anchor, |
| 138 | network: Network::Mainnet, |
| 139 | secret_ref: ProtectedSecretRef { |
| 140 | value: "wallet:ton-connect:mnemonic".to_owned(), |
| 141 | }, |
| 142 | }; |
| 143 | // Upstream verifies that the descriptor's anchor key derives its address. |
| 144 | protocol( |
| 145 | "Validate wallet account", |
| 146 | lifecycle.ton_connect_account(descriptor.clone()), |
| 147 | )?; |
| 148 | let derived = protocol( |
| 149 | "Derive TON Connect session", |
| 150 | futures::executor::block_on(lifecycle.derive_ton_connect_session( |
| 151 | TonConnectDerivedSessionRequest { |
| 152 | descriptor: descriptor.clone(), |
| 153 | dapp_client_id: p.dapp_client_id.to_lowercase(), |
| 154 | nonce: protocol("Decode session nonce", STANDARD.decode(&p.session_nonce))?, |
| 155 | }, |
| 156 | )), |
| 157 | )?; |
| 158 | if protocol( |
| 159 | "Decode wallet public key", |
| 160 | STANDARD.decode(&p.wallet_public_key), |
| 161 | )? != derived.signing_public_key() |
| 162 | { |
| 163 | return Err(invalid( |
| 164 | "Recovery phrase does not match the current wallet signing key", |
| 165 | )); |
| 166 | } |
| 167 | if let Some(expected) = &p.client_id { |
| 168 | if !derived.public_key_hex().eq_ignore_ascii_case(expected) { |
| 169 | return Err(invalid( |
| 170 | "Derived session key does not match the registered client ID", |
| 171 | )); |
| 172 | } |
| 173 | } |
| 174 | Ok(Self { |
| 175 | derived, |
| 176 | lifecycle, |
| 177 | descriptor, |
| 178 | }) |
| 179 | } |
| 180 |
| 181 | fn client_id(&self) -> String { |
| 182 | self.derived.public_key_hex() |
| 183 | } |
| 184 |
| 185 | fn encrypt(&self, event: &Value) -> Result<String> { |
| 186 | let body = protocol("Serialize TON Connect response", serde_json::to_vec(event))?; |
| 187 | Ok(STANDARD.encode(protocol( |
| 188 | "Encrypt TON Connect response", |
| 189 | self.derived.encrypt_envelope(body), |
| 190 | )?)) |
| 191 | } |
| 192 | } |
| 193 |
| 194 | /// Stateless cryptographic adapter. Java owns TON Connect envelopes, methods, |
| 195 | /// capabilities and MTProto workflow; secret keys never leave this call. |
| 196 | #[uniffi::export] |
| 197 | pub fn gram_ton_connect_crypto(phrase: String, parameters: String) -> Result<String> { |
| 198 | let p: Parameters = protocol("Parse crypto parameters", serde_json::from_str(¶meters))?; |
| 199 | let session = Session::new(phrase, &p)?; |
| 200 | let mut output = json!({"clientId": session.client_id()}); |
| 201 | if let Some(challenge) = &p.challenge { |
| 202 | let bytes = protocol("Decode challenge", STANDARD.decode(challenge))?; |
| 203 | let answer = Zeroizing::new(protocol( |
| 204 | "Open session challenge", |
| 205 | session.derived.open_challenge(bytes), |
| 206 | )?); |
| 207 | output["challengeAnswer"] = json!(STANDARD.encode(answer.as_slice())); |
| 208 | } |
| 209 | if let Some(body) = &p.decrypt { |
| 210 | let body = protocol("Decode encrypted body", STANDARD.decode(body))?; |
| 211 | if body.len() < 40 || body.len() > 1024 * 1024 { |
| 212 | return Err(invalid("Encrypted body must be between 40 bytes and 1 MiB")); |
| 213 | } |
| 214 | let plaintext = Zeroizing::new(protocol( |
| 215 | "Decrypt request", |
| 216 | session.derived.decrypt_envelope(body), |
| 217 | )?); |
| 218 | output["plaintext"] = json!(protocol( |
| 219 | "Decode UTF-8 request", |
| 220 | std::str::from_utf8(&plaintext) |
| 221 | )?); |
| 222 | } |
| 223 | if let Some(message) = &p.encrypt { |
| 224 | output["body"] = json!(session.encrypt(message)?); |
| 225 | } |
| 226 | if p.account { |
| 227 | let account = protocol( |
| 228 | "Get wallet account", |
| 229 | session |
| 230 | .lifecycle |
| 231 | .ton_connect_account(session.descriptor.clone()), |
| 232 | )?; |
| 233 | output["account"] = json!({"name":"ton_addr", "address":account.address, |
| 234 | "network":account.network, "walletStateInit":account.wallet_state_init, |
| 235 | "publicKey":hex::encode(protocol("Decode signing key", STANDARD.decode(&p.wallet_public_key))?)}); |
| 236 | } |
| 237 | if let Some(domain) = &p.proof_domain { |
| 238 | // The import proof uses this same signing format. Keep its domain |
| 239 | // unavailable to dApps even if a caller skips the Java validation. |
| 240 | if domain |
| 241 | .trim_end_matches('.') |
| 242 | .eq_ignore_ascii_case("telegram.org") |
| 243 | { |
| 244 | return Err(invalid( |
| 245 | "The telegram.org proof domain is reserved for wallet import", |
| 246 | )); |
| 247 | } |
| 248 | let timestamp = p |
| 249 | .timestamp |
| 250 | .filter(|t| *t > 0) |
| 251 | .ok_or_else(|| invalid("Missing proof timestamp"))?; |
| 252 | let payload = p |
| 253 | .proof_payload |
| 254 | .as_ref() |
| 255 | .ok_or_else(|| invalid("Missing proof payload"))?; |
| 256 | let signed = protocol( |
| 257 | "Sign proof", |
| 258 | futures::executor::block_on(session.lifecycle.sign_ton_connect_proof( |
| 259 | TonConnectProofSignRequest { |
| 260 | descriptor: session.descriptor.clone(), |
| 261 | domain: domain.clone(), |
| 262 | timestamp, |
| 263 | payload: payload.clone(), |
| 264 | }, |
| 265 | )), |
| 266 | )?; |
| 267 | output["signature"] = json!(STANDARD.encode(signed.signature)); |
| 268 | } |
| 269 | if let Some(payload) = &p.sign_data { |
| 270 | use ton_connect_core::SignDataPayload; |
| 271 | let value = protocol("Serialize signing payload", serde_json::to_value(payload))?; |
| 272 | let request = TonConnectSignDataRequest { |
| 273 | payload: match payload { |
| 274 | SignDataPayload::Text { text, .. } => { |
| 275 | TonConnectSignDataPayload::Text { text: text.clone() } |
| 276 | } |
| 277 | SignDataPayload::Binary { bytes, .. } => TonConnectSignDataPayload::Binary { |
| 278 | bytes: bytes.as_str().to_owned(), |
| 279 | }, |
| 280 | SignDataPayload::Cell { schema, cell, .. } => TonConnectSignDataPayload::Cell { |
| 281 | schema: schema.clone(), |
| 282 | cell: cell.as_str().to_owned(), |
| 283 | }, |
| 284 | }, |
| 285 | network: value |
| 286 | .get("network") |
| 287 | .and_then(Value::as_str) |
| 288 | .map(str::to_owned), |
| 289 | from: value.get("from").and_then(Value::as_str).map(str::to_owned), |
| 290 | }; |
| 291 | let domain = p |
| 292 | .sign_domain |
| 293 | .as_deref() |
| 294 | .filter(|d| !d.is_empty()) |
| 295 | .ok_or_else(|| invalid("Missing signing domain"))?; |
| 296 | let timestamp = p |
| 297 | .timestamp |
| 298 | .filter(|t| *t > 0) |
| 299 | .ok_or_else(|| invalid("Missing signing timestamp"))?; |
| 300 | let signed = protocol( |
| 301 | "Sign data", |
| 302 | futures::executor::block_on(session.lifecycle.sign_ton_connect_data( |
| 303 | TonConnectSignDataSignRequest { |
| 304 | descriptor: session.descriptor.clone(), |
| 305 | request, |
| 306 | domain: domain.to_owned(), |
| 307 | timestamp, |
| 308 | }, |
| 309 | )), |
| 310 | )?; |
| 311 | let account = protocol( |
| 312 | "Get signing account", |
| 313 | session |
| 314 | .lifecycle |
| 315 | .ton_connect_account(session.descriptor.clone()), |
| 316 | )?; |
| 317 | output["signature"] = json!(STANDARD.encode(signed.signature)); |
| 318 | output["address"] = json!(account.address); |
| 319 | } |
| 320 | Ok(output.to_string()) |
| 321 | } |
| 322 |
| 323 | #[cfg(test)] |
| 324 | mod tests { |
| 325 | use super::*; |
| 326 | use ton::{ |
| 327 | block_tlb::StateInit, |
| 328 | ton_core::{cell::TonHash, traits::tlb::TLB}, |
| 329 | ton_wallet::{WALLET_SUBWALLET_ID_DEFAULT, WalletData, WalletVersion}, |
| 330 | }; |
| 331 | use ton_connect_core::{ |
| 332 | ClientId, Ed25519PublicKey, Ed25519Signature, RawAccountAddress, SessionCrypto, |
| 333 | SignatureDomain, ton_proof_signing_hash, verify_signature, |
| 334 | }; |
| 335 | const PHRASE: &str = |
| 336 | "notice tortoise soup strong gun divide offer process salon siren general carry"; |
| 337 | const ROTATED: &str = "notice tortoise soup strong gun divide offer process salon siren general carry clump left year void clutch tool case burden fix income champion lounge"; |
| 338 | fn parameters(peer: &SessionCrypto, phrase: &str) -> Value { |
| 339 | let anchor = rotation_mnemonic_public_key( |
| 340 | phrase |
| 341 | .split_whitespace() |
| 342 | .take(12) |
| 343 | .collect::<Vec<_>>() |
| 344 | .join(" "), |
| 345 | ) |
| 346 | .unwrap(); |
| 347 | let code = WalletVersion::get_code(WalletVersion::Wallet) |
| 348 | .unwrap() |
| 349 | .clone(); |
| 350 | let data = WalletData::new( |
| 351 | WALLET_SUBWALLET_ID_DEFAULT, |
| 352 | TonHash::from_slice(&anchor).unwrap(), |
| 353 | ) |
| 354 | .to_cell() |
| 355 | .unwrap(); |
| 356 | let address = StateInit::new(code, data) |
| 357 | .derive_address(0) |
| 358 | .unwrap() |
| 359 | .to_hex(); |
| 360 | let current_key = rotation_mnemonic_public_key( |
| 361 | phrase.split_whitespace().collect::<Vec<_>>()[phrase.split_whitespace().count() - 12..] |
| 362 | .join(" "), |
| 363 | ) |
| 364 | .unwrap(); |
| 365 | json!({"dappClientId":peer.client_id().to_string(),"sessionNonce":STANDARD.encode([7u8;32]), |
| 366 | "walletPublicKey":STANDARD.encode(current_key),"walletAddress":address}) |
| 367 | } |
| 368 |
| 369 | fn call(phrase: &str, p: &Value) -> Value { |
| 370 | serde_json::from_str(&gram_ton_connect_crypto(phrase.to_owned(), p.to_string()).unwrap()) |
| 371 | .unwrap() |
| 372 | } |
| 373 |
| 374 | #[test] |
| 375 | fn derivation_matches_independent_vector() { |
| 376 | let peer = SessionCrypto::generate().unwrap(); |
| 377 | let mut p = parameters(&peer, PHRASE); |
| 378 | p["dappClientId"] = json!("11".repeat(32)); |
| 379 | // Reference vector from Python hashlib/hmac and OpenSSL X25519. |
| 380 | p["sessionNonce"] = json!(STANDARD.encode([7u8; 32])); |
| 381 | assert_eq!( |
| 382 | call(PHRASE, &p)["clientId"], |
| 383 | "908ba37dfad5b2d9898491ec4c8955f9342407261291d4065059d339d2c1f679" |
| 384 | ); |
| 385 | } |
| 386 |
| 387 | #[test] |
| 388 | fn boxes_and_challenges_interoperate_and_authenticate() { |
| 389 | let peer = SessionCrypto::generate().unwrap(); |
| 390 | let mut p = parameters(&peer, PHRASE); |
| 391 | let identity = call(PHRASE, &p); |
| 392 | let client: ClientId = identity["clientId"].as_str().unwrap().parse().unwrap(); |
| 393 | p["clientId"] = identity["clientId"].clone(); |
| 394 | let request = br#"{"id":"request-ABC","method":"disconnect","params":[]}"#; |
| 395 | p["decrypt"] = json!(STANDARD.encode(peer.encrypt(client, request).unwrap())); |
| 396 | let ephemeral = SessionCrypto::generate().unwrap(); |
| 397 | let mut challenge = ephemeral.client_id().to_bytes().to_vec(); |
| 398 | challenge.extend(ephemeral.encrypt(client, &[42; 32]).unwrap()); |
| 399 | p["challenge"] = json!(STANDARD.encode(challenge)); |
| 400 | p["encrypt"] = json!({"id":"request-ABC","result":{}}); |
| 401 | let result = call(PHRASE, &p); |
| 402 | assert_eq!(result["plaintext"], std::str::from_utf8(request).unwrap()); |
| 403 | assert_eq!(result["challengeAnswer"], STANDARD.encode([42; 32])); |
| 404 | let response: Value = serde_json::from_slice( |
| 405 | &peer |
| 406 | .decrypt( |
| 407 | client, |
| 408 | &STANDARD.decode(result["body"].as_str().unwrap()).unwrap(), |
| 409 | ) |
| 410 | .unwrap(), |
| 411 | ) |
| 412 | .unwrap(); |
| 413 | assert_eq!(response, p["encrypt"]); |
| 414 | assert_ne!(result["body"], call(PHRASE, &p)["body"]); |
| 415 | let mut bad = p.clone(); |
| 416 | bad["clientId"] = json!(peer.client_id().to_string()); |
| 417 | assert!(gram_ton_connect_crypto(PHRASE.to_owned(), bad.to_string()).is_err()); |
| 418 | let mut body = STANDARD.decode(p["decrypt"].as_str().unwrap()).unwrap(); |
| 419 | *body.last_mut().unwrap() ^= 1; |
| 420 | p["decrypt"] = json!(STANDARD.encode(body)); |
| 421 | assert!(gram_ton_connect_crypto(PHRASE.to_owned(), p.to_string()).is_err()); |
| 422 | } |
| 423 |
| 424 | #[test] |
| 425 | fn rotated_session_preserves_sign_message_envelopes_and_rejects_stale_keys() { |
| 426 | let peer = SessionCrypto::generate().unwrap(); |
| 427 | let mut p = parameters(&peer, ROTATED); |
| 428 | let identity = call(ROTATED, &p); |
| 429 | let client: ClientId = identity["clientId"].as_str().unwrap().parse().unwrap(); |
| 430 | let request = br#"{"id":"message-ABC","method":"signMessage","params":["{}"]}"#; |
| 431 | p["decrypt"] = json!(STANDARD.encode(peer.encrypt(client, request).unwrap())); |
| 432 | p["encrypt"] = json!({"id":"message-ABC", "result":{"internalBoc":"opaque"}}); |
| 433 | let result = call(ROTATED, &p); |
| 434 | assert_eq!(result["plaintext"], std::str::from_utf8(request).unwrap()); |
| 435 | let response: Value = serde_json::from_slice( |
| 436 | &peer |
| 437 | .decrypt( |
| 438 | client, |
| 439 | &STANDARD.decode(result["body"].as_str().unwrap()).unwrap(), |
| 440 | ) |
| 441 | .unwrap(), |
| 442 | ) |
| 443 | .unwrap(); |
| 444 | assert_eq!(response, p["encrypt"]); |
| 445 | p["walletPublicKey"] = |
| 446 | json!(STANDARD.encode(rotation_mnemonic_public_key(ROTATED.to_owned()).unwrap())); |
| 447 | assert!(gram_ton_connect_crypto(ROTATED.to_owned(), p.to_string()).is_err()); |
| 448 | } |
| 449 |
| 450 | #[test] |
| 451 | fn signs_all_data_types_with_the_current_key_and_bound_context() { |
| 452 | for phrase in [PHRASE, ROTATED] { |
| 453 | let peer = SessionCrypto::generate().unwrap(); |
| 454 | let mut p = parameters(&peer, phrase); |
| 455 | p["signDomain"] = json!("example.com"); |
| 456 | p["timestamp"] = json!(1700000000u64); |
| 457 | for payload in [ |
| 458 | json!({"type":"text", "text":"Hello 🌍\nKeep this line", "network":"-239"}), |
| 459 | json!({"type":"binary", "bytes":"AAEC/f7/"}), |
| 460 | json!({"type":"cell", "schema":"empty$_ = Empty;", "cell":"te6ccgEBAQEAAgAAAA=="}), |
| 461 | ] { |
| 462 | p["signData"] = payload.clone(); |
| 463 | let signed = call(phrase, &p); |
| 464 | let mut result: ton_connect_core::SignDataResult = serde_json::from_value(json!({ |
| 465 | "signature":signed["signature"], "address":signed["address"], "domain":"example.com", |
| 466 | "timestamp":1700000000u64, "payload":payload |
| 467 | })).unwrap(); |
| 468 | let key = Ed25519PublicKey::from_bytes( |
| 469 | rotation_mnemonic_public_key( |
| 470 | phrase.split_whitespace().collect::<Vec<_>>() |
| 471 | [phrase.split_whitespace().count() - 12..] |
| 472 | .join(" "), |
| 473 | ) |
| 474 | .unwrap() |
| 475 | .try_into() |
| 476 | .unwrap(), |
| 477 | ); |
| 478 | assert!(result.verify(&key).unwrap()); |
| 479 | result.domain = "other.example".to_owned(); |
| 480 | assert!(!result.verify(&key).unwrap()); |
| 481 | result.domain = "example.com".to_owned(); |
| 482 | result.timestamp += 1; |
| 483 | assert!(!result.verify(&key).unwrap()); |
| 484 | } |
| 485 | for payload in [ |
| 486 | json!({"type":"text", "text":"test", "network":"-3"}), |
| 487 | json!({"type":"text", "text":"test", "from":"0:1111111111111111111111111111111111111111111111111111111111111111"}), |
| 488 | json!({"type":"binary", "bytes":"bad!"}), |
| 489 | json!({"type":"cell", "schema":"empty$_ = Empty;", "cell":"bad"}), |
| 490 | ] { |
| 491 | p["signData"] = payload; |
| 492 | assert!(gram_ton_connect_crypto(phrase.to_owned(), p.to_string()).is_err()); |
| 493 | } |
| 494 | } |
| 495 | } |
| 496 |
| 497 | #[test] |
| 498 | fn proof_uses_current_key_and_refuses_import_domain() { |
| 499 | for phrase in [PHRASE, ROTATED] { |
| 500 | let peer = SessionCrypto::generate().unwrap(); |
| 501 | let mut p = parameters(&peer, phrase); |
| 502 | p["account"] = json!(true); |
| 503 | p["proofDomain"] = json!("example.com"); |
| 504 | p["proofPayload"] = json!("challenge"); |
| 505 | p["timestamp"] = json!(1700000000u64); |
| 506 | let result = call(phrase, &p); |
| 507 | let address: RawAccountAddress = result["account"]["address"] |
| 508 | .as_str() |
| 509 | .unwrap() |
| 510 | .parse() |
| 511 | .unwrap(); |
| 512 | let hash = |
| 513 | ton_proof_signing_hash(&address, "example.com", 1700000000, "challenge").unwrap(); |
| 514 | let signature = Ed25519Signature::from_bytes( |
| 515 | STANDARD |
| 516 | .decode(result["signature"].as_str().unwrap()) |
| 517 | .unwrap() |
| 518 | .try_into() |
| 519 | .unwrap(), |
| 520 | ); |
| 521 | let key = Ed25519PublicKey::from_bytes( |
| 522 | rotation_mnemonic_public_key( |
| 523 | phrase.split_whitespace().collect::<Vec<_>>() |
| 524 | [phrase.split_whitespace().count() - 12..] |
| 525 | .join(" "), |
| 526 | ) |
| 527 | .unwrap() |
| 528 | .try_into() |
| 529 | .unwrap(), |
| 530 | ); |
| 531 | assert!(verify_signature(&hash, &signature, &key, SignatureDomain::Empty).unwrap()); |
| 532 | for domain in ["telegram.org", "TELEGRAM.ORG", "telegram.org."] { |
| 533 | p["proofDomain"] = json!(domain); |
| 534 | assert!(gram_ton_connect_crypto(phrase.to_owned(), p.to_string()).is_err()); |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 |