| 5 | #include <functional> |
| 6 | #include <algorithm> |
| 7 |
| 8 | #include <charconv> |
| 9 | #include <limits> |
| 10 | #include <mutex> |
| 11 | #include <unordered_map> |
| 12 |
| 13 | namespace { |
| 14 | namespace we = wallet_engine; |
| 15 |
| 16 | we::NftTransferIntent nft_transfer_intent(JNIEnv *env, jbyteArray comment_bytes, const std::string &recipient, const std::string &nft, |
| 17 | jlong attached, jlong forward) { |
| 18 | if (!we::is_valid_ton_address(recipient) || !we::is_valid_ton_address(nft)) |
| 19 | throw std::invalid_argument("Valid recipient and NFT addresses are required"); |
| 20 | if (forward < 0 || attached <= forward) |
| 21 | throw std::invalid_argument("NFT attached amount must exceed its forward amount"); |
| 22 | we::NftTransferPayload payload = we::NftTransferPayload::kEmpty{}; |
| 23 | if (comment_bytes) { |
| 24 | const auto length = env->GetArrayLength(comment_bytes); |
| 25 | if (length > 960) throw std::invalid_argument("Comment exceeds 960 UTF-8 bytes"); |
| 26 | if (length > 0) { |
| 27 | std::string comment(static_cast<size_t>(length), '\0'); |
| 28 | env->GetByteArrayRegion(comment_bytes, 0, length, reinterpret_cast<jbyte *>(comment.data())); |
| 29 | if (env->ExceptionCheck()) throw std::runtime_error("Could not read NFT comment"); |
| 30 | payload = we::NftTransferPayload::kComment{comment}; |
| 31 | } |
| 32 | } |
| 33 | return {nft, recipient, |
| 34 | we::NftTransferFunding::kExact{std::to_string(attached), std::to_string(forward)}, |
| 35 | payload, we::SendExpiration::kEngineDefault{}}; |
| 36 | } |
| 37 |
| 38 | struct SensitiveString { |
| 39 | std::string value; |
| 40 |
| 41 | explicit SensitiveString(size_t size) : value(size, '\0') {} |
| 42 | SensitiveString(const SensitiveString &) = delete; |
| 43 | SensitiveString &operator=(const SensitiveString &) = delete; |
| 44 |
| 45 | ~SensitiveString() { |
| 46 | // Volatile writes keep this cleanup from being optimized away. |
| 47 | volatile char *data = value.data(); |
| 48 | for (size_t i = 0; i < value.size(); ++i) data[i] = 0; |
| 49 | } |
| 50 | }; |
| 51 |
| 52 | // This host is scoped to a user-requested local operation. Nothing is persisted; |
| 53 | // the mnemonic is released when the synchronous lifecycle calls finish. |
| 54 | class EphemeralWalletHost final : public we::WalletPlatformHost { |
| 55 | std::unique_ptr<SensitiveString> secret_; |
| 56 | std::string secret_ref_; |
| 57 | const we::SecretAccessReason reason_; |
| 58 |
| 59 | [[noreturn]] static void unavailable() { |
| 60 | we::protected_secret_host_error::Failed error; |
| 61 | error.kind = we::ProtectedSecretHostErrorKind::kUnavailable; |
| 62 | error.diagnostic = "No recovery phrase authorized for this operation"; |
| 63 | throw error; |
| 64 | } |
| 65 |
| 66 | public: |
| 67 | explicit EphemeralWalletHost(we::SecretAccessReason reason) : reason_(reason) {} |
| 68 |
| 69 | void store_protected_secret(const we::ProtectedSecretStore &request) override { |
| 70 | if (secret_) unavailable(); |
| 71 | auto secret = std::make_unique<SensitiveString>(request.bytes.size()); |
| 72 | std::copy(request.bytes.begin(), request.bytes.end(), secret->value.begin()); |
| 73 | secret_ref_ = request.secret_ref.value; |
| 74 | secret_ = std::move(secret); |
| 75 | } |
| 76 |
| 77 | std::vector<uint8_t> read_protected_secret(const we::ProtectedSecretRead &request) override { |
| 78 | if (!secret_ || request.secret_ref.value != secret_ref_ |
| 79 | || request.reason != reason_) unavailable(); |
| 80 | return {secret_->value.begin(), secret_->value.end()}; |
| 81 | } |
| 82 |
| 83 | void delete_protected_secret(const we::ProtectedSecretRef &) override { unavailable(); } |
| 84 | std::optional<we::JournalRecord> load_journal(const we::JournalKey &) override { |
| 85 | throw std::logic_error("Local wallet operation does not use a journal"); |
| 86 | } |
| 87 | we::JournalCompareExchangeResult compare_exchange_journal(const we::JournalCompareExchange &) override { |
| 88 | throw std::logic_error("Local wallet operation does not use a journal"); |
| 89 | } |
| 90 | }; |
| 91 |
| 92 | struct ImportProofRequest { |
| 93 | we::ImportWalletRequest value{"import-proof", we::Network::kMainnet, {}}; |
| 94 | explicit ImportProofRequest(const std::string &phrase) { |
| 95 | value.recovery_words.reserve(24); |
| 96 | const char *whitespace = " \t\r\n\f\v"; |
| 97 | for (size_t start = phrase.find_first_not_of(whitespace); start != std::string::npos;) { |
| 98 | const auto end = phrase.find_first_of(whitespace, start); |
| 99 | value.recovery_words.emplace_back(phrase, start, |
| 100 | end == std::string::npos ? std::string::npos : end - start); |
| 101 | start = end == std::string::npos ? end : phrase.find_first_not_of(whitespace, end); |
| 102 | } |
| 103 | } |
| 104 | ~ImportProofRequest() { |
| 105 | for (auto &word : value.recovery_words) { |
| 106 | volatile char *data = word.data(); |
| 107 | for (size_t i = 0; i < word.size(); ++i) data[i] = 0; |
| 108 | } |
| 109 | } |
| 110 | }; |
| 111 |
| 112 | class OfflineWalletTransport final : public we::WalletStatuslessHost { |
| 113 | public: |
| 114 | std::vector<uint8_t> execute_statusless(const we::HttpRequest &) override { |
| 115 | throw std::logic_error("Local wallet operation cannot access the network"); |
| 116 | } |
| 117 | void cancel_statusless(const we::HttpRequestId &) override {} |
| 118 | }; |
| 119 |
| 120 | // Host callbacks may run on a Rust worker as well as a Java caller thread. |
| 121 | class JavaEnv { |
| 122 | public: |
| 123 | JNIEnv *env = nullptr; |
| 124 | explicit JavaEnv(JavaVM *vm) : vm_(vm) { |
| 125 | const jint status = vm_->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6); |
| 126 | if (status == JNI_EDETACHED) { |
| 127 | #ifdef __ANDROID__ |
| 128 | if (vm_->AttachCurrentThread(&env, nullptr) != JNI_OK) |
| 129 | #else |
| 130 | if (vm_->AttachCurrentThread(reinterpret_cast<void **>(&env), nullptr) != JNI_OK) |
| 131 | #endif |
| 132 | throw std::runtime_error("Could not attach wallet callback thread"); |
| 133 | attached_ = true; |
| 134 | } else if (status != JNI_OK) { |
| 135 | throw std::runtime_error("Could not access wallet callback thread"); |
| 136 | } |
| 137 | if (env->PushLocalFrame(16) != JNI_OK) { |
| 138 | if (attached_) vm_->DetachCurrentThread(); |
| 139 | throw std::runtime_error("Could not allocate wallet callback references"); |
| 140 | } |
| 141 | } |
| 142 | ~JavaEnv() { |
| 143 | env->PopLocalFrame(nullptr); |
| 144 | if (attached_) vm_->DetachCurrentThread(); |
| 145 | } |
| 146 | private: |
| 147 | JavaVM *vm_; |
| 148 | bool attached_ = false; |
| 149 | }; |
| 150 |
| 151 | class WalletHosts final : public we::WalletStatuslessHost, public we::WalletPlatformHost { |
| 152 | public: |
| 153 | std::weak_ptr<we::WalletClient> client; |
| 154 | const SensitiveString *secret = nullptr; |
| 155 | std::string secret_ref; |
| 156 | we::SecretAccessReason secret_reason = we::SecretAccessReason::kSignTransfer; |
| 157 | std::function<void(const we::SendSnapshot &)> on_state; |
| 158 |
| 159 | void report_state() { |
| 160 | if (on_state) { |
| 161 | if (auto value = client.lock()) on_state(value->snapshot().send); |
| 162 | } |
| 163 | } |
| 164 |
| 165 | WalletHosts(JNIEnv *env, jobject transport, std::string journal_directory) |
| 166 | : journal_(std::move(journal_directory)) { |
| 167 | if (!transport || env->GetJavaVM(&vm_) != JNI_OK) |
| 168 | throw std::invalid_argument("Wallet transport is required"); |
| 169 | jclass cls = env->GetObjectClass(transport); |
| 170 | execute_ = env->GetMethodID(cls, "execute", "(JLjava/lang/String;Z[BJ)[B"); |
| 171 | cancel_ = env->GetMethodID(cls, "cancel", "(J)V"); |
| 172 | env->DeleteLocalRef(cls); |
| 173 | jclass error_cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$HttpTransport$HostException"); |
| 174 | if (!error_cls || !execute_ || !cancel_) |
| 175 | throw std::runtime_error("Could not resolve wallet transport callbacks"); |
| 176 | error_kind_ = env->GetFieldID(error_cls, "kind", "I"); |
| 177 | if (!error_kind_) { |
| 178 | env->DeleteLocalRef(error_cls); |
| 179 | throw std::runtime_error("Could not resolve wallet transport error"); |
| 180 | } |
| 181 | error_class_ = static_cast<jclass>(env->NewGlobalRef(error_cls)); |
| 182 | env->DeleteLocalRef(error_cls); |
| 183 | if (!error_class_) throw std::bad_alloc(); |
| 184 | transport_ = env->NewGlobalRef(transport); |
| 185 | if (!transport_) { |
| 186 | env->DeleteGlobalRef(error_class_); |
| 187 | throw std::bad_alloc(); |
| 188 | } |
| 189 | } |
| 190 |
| 191 | ~WalletHosts() override { |
| 192 | try { |
| 193 | JavaEnv java(vm_); |
| 194 | java.env->DeleteGlobalRef(transport_); |
| 195 | java.env->DeleteGlobalRef(error_class_); |
| 196 | } catch (...) { } |
| 197 | } |
| 198 |
| 199 | std::vector<uint8_t> execute_statusless(const we::HttpRequest &request) override { |
| 200 | report_state(); |
| 201 | JavaEnv java(vm_); |
| 202 | JNIEnv *env = java.env; |
| 203 | jstring url = env->NewStringUTF(request.url.c_str()); |
| 204 | if (!url) check_exception(env); |
| 205 | jbyteArray body = env->NewByteArray(static_cast<jsize>(request.body.size())); |
| 206 | if (!body) check_exception(env); |
| 207 | env->SetByteArrayRegion(body, 0, static_cast<jsize>(request.body.size()), |
| 208 | reinterpret_cast<const jbyte *>(request.body.data())); |
| 209 | check_exception(env); |
| 210 | auto response = static_cast<jbyteArray>(env->CallObjectMethod(transport_, execute_, |
| 211 | static_cast<jlong>(request.id.value), url, |
| 212 | static_cast<jboolean>(request.method == we::HttpMethod::kPost), body, |
| 213 | static_cast<jlong>(request.timeout_ms))); |
| 214 | check_exception(env); |
| 215 | if (!response) throw transport_error(7); |
| 216 | std::vector<uint8_t> result(env->GetArrayLength(response)); |
| 217 | env->GetByteArrayRegion(response, 0, static_cast<jsize>(result.size()), |
| 218 | reinterpret_cast<jbyte *>(result.data())); |
| 219 | check_exception(env); |
| 220 | return result; |
| 221 | } |
| 222 |
| 223 | void cancel_statusless(const we::HttpRequestId &id) override { |
| 224 | JavaEnv java(vm_); |
| 225 | java.env->CallVoidMethod(transport_, cancel_, static_cast<jlong>(id.value)); |
| 226 | // Cancellation is best-effort and must not leave a pending JNI exception. |
| 227 | if (java.env->ExceptionCheck()) java.env->ExceptionClear(); |
| 228 | } |
| 229 |
| 230 | std::vector<uint8_t> read_protected_secret(const we::ProtectedSecretRead &request) override { |
| 231 | report_state(); |
| 232 | if (!secret || request.secret_ref.value != secret_ref || request.reason != secret_reason) |
| 233 | throw secret_unavailable(); |
| 234 | return {secret->value.begin(), secret->value.end()}; |
| 235 | } |
| 236 |
| 237 | void store_protected_secret(const we::ProtectedSecretStore &) override { |
| 238 | throw secret_unavailable(); |
| 239 | } |
| 240 |
| 241 | void delete_protected_secret(const we::ProtectedSecretRef &) override { |
| 242 | throw secret_unavailable(); |
| 243 | } |
| 244 |
| 245 | std::optional<we::JournalRecord> load_journal(const we::JournalKey &key) override { |
| 246 | report_state(); |
| 247 | try { return journal_.access(key).current; } |
| 248 | catch (...) { throw journal_unavailable(); } |
| 249 | } |
| 250 |
| 251 | we::JournalCompareExchangeResult compare_exchange_journal(const we::JournalCompareExchange &mutation) override { |
| 252 | report_state(); |
| 253 | try { return journal_.access(mutation.key, &mutation); } |
| 254 | catch (...) { throw journal_unavailable(); } |
| 255 | } |
| 256 |
| 257 | private: |
| 258 | WalletJournal journal_; |
| 259 | JavaVM *vm_ = nullptr; |
| 260 | jobject transport_ = nullptr; |
| 261 | jclass error_class_ = nullptr; |
| 262 | jmethodID execute_ = nullptr; |
| 263 | jmethodID cancel_ = nullptr; |
| 264 | jfieldID error_kind_ = nullptr; |
| 265 |
| 266 | static we::statusless_host_error::Failed transport_error(jint kind) { |
| 267 | we::statusless_host_error::Failed error; |
| 268 | error.kind = static_cast<we::StatuslessHostErrorKind>(kind >= 1 && kind <= 7 ? kind : 7); |
| 269 | error.diagnostic = kind == 2 ? "Wallet provider request timed out" |
| 270 | : kind == 6 ? "Wallet provider request was cancelled" : "Wallet provider request failed"; |
| 271 | return error; |
| 272 | } |
| 273 |
| 274 | void check_exception(JNIEnv *env) const { |
| 275 | if (!env->ExceptionCheck()) return; |
| 276 | jthrowable exception = env->ExceptionOccurred(); |
| 277 | env->ExceptionClear(); |
| 278 | jint kind = env->IsInstanceOf(exception, error_class_) ? env->GetIntField(exception, error_kind_) : 7; |
| 279 | env->DeleteLocalRef(exception); |
| 280 | throw transport_error(kind); |
| 281 | } |
| 282 |
| 283 | static we::protected_secret_host_error::Failed secret_unavailable() { |
| 284 | we::protected_secret_host_error::Failed error; |
| 285 | error.kind = we::ProtectedSecretHostErrorKind::kUnavailable; |
| 286 | error.diagnostic = "No recovery phrase authorized for this operation"; |
| 287 | return error; |
| 288 | } |
| 289 |
| 290 | static we::journal_host_error::Failed journal_unavailable() { |
| 291 | we::journal_host_error::Failed error; |
| 292 | error.kind = we::JournalHostErrorKind::kUnavailable; |
| 293 | error.diagnostic = "Wallet journal storage failed"; |
| 294 | return error; |
| 295 | } |
| 296 | }; |
| 297 |
| 298 | std::mutex clients_mutex; |
| 299 | struct Client { |
| 300 | std::shared_ptr<we::WalletClient> wallet; |
| 301 | std::shared_ptr<WalletHosts> hosts; |
| 302 | }; |
| 303 | std::unordered_map<jlong, Client> clients; |
| 304 | jlong next_handle = 1; |
| 305 |
| 306 | Client get_client(jlong handle) { |
| 307 | std::lock_guard<std::mutex> lock(clients_mutex); |
| 308 | const auto it = clients.find(handle); |
| 309 | if (it == clients.end()) throw std::runtime_error("NO_WALLET_ENGINE"); |
| 310 | return it->second; |
| 311 | } |
| 312 |
| 313 | std::string java_string(JNIEnv *env, jstring value) { |
| 314 | if (!value) throw std::invalid_argument("Required string is missing"); |
| 315 | const char *chars = env->GetStringUTFChars(value, nullptr); |
| 316 | if (!chars) throw std::bad_alloc(); |
| 317 | try { |
| 318 | std::string result(chars); |
| 319 | env->ReleaseStringUTFChars(value, chars); |
| 320 | return result; |
| 321 | } catch (...) { |
| 322 | env->ReleaseStringUTFChars(value, chars); |
| 323 | throw; |
| 324 | } |
| 325 | } |
| 326 |
| 327 | we::SendIntent transfer_intent( |
| 328 | const std::string &address, jlong amount, |
| 329 | we::SendMessageBody body) { |
| 330 | if (amount < 0) throw std::invalid_argument("Transfer amount must not be negative"); |
| 331 | const auto parsed = we::parse_ton_address(address); |
| 332 | const auto friendly = std::get_if<we::TonAddressFormat::kUserFriendly>(&parsed.format.get_variant()); |
| 333 | if (friendly != nullptr && friendly->testnet) { |
| 334 | throw std::invalid_argument("Testnet-only recipient is not allowed"); |
| 335 | } |
| 336 | // Raw addresses carry no bounce flag; retain the non-bounceable default. |
| 337 | const bool bounce = friendly != nullptr && friendly->bounceable; |
| 338 | return {we::SendExpiration::kEngineDefault{}, { |
| 339 | we::SendMessage{address, we::SendAmount::kExact{std::to_string(amount)}, |
| 340 | std::move(body), bounce, std::nullopt} |
| 341 | }}; |
| 342 | } |
| 343 |
| 344 | we::SendIntent transfer_intent(const std::string &address, jlong amount) { |
| 345 | return transfer_intent(address, amount, we::SendMessageBody::kEmpty{}); |
| 346 | } |
| 347 |
| 348 | // Local references are scoped to the native entry point that creates the result. |
| 349 | class Transaction { |
| 350 | JNIEnv *env_; |
| 351 | jclass cls_; |
| 352 | jclass engine_cls_; |
| 353 | public: |
| 354 | jobject object; |
| 355 | Transaction(JNIEnv *env, const std::string &address, jlong amount) : env_(env) { |
| 356 | engine_cls_ = env_->FindClass("org/telegram/ui/Wallet/WalletEngine2"); |
| 357 | if (!engine_cls_) throw std::runtime_error("Could not resolve wallet engine"); |
| 358 | auto factory = env_->GetStaticMethodID(engine_cls_, "createTransaction", |
| 359 | "(Ljava/lang/String;J)Lorg/telegram/tgnet/tl/TL_wallet$walletTransaction;"); |
| 360 | if (!factory) throw std::runtime_error("Could not resolve wallet transaction factory"); |
| 361 | auto destination = env_->NewStringUTF(address.c_str()); |
| 362 | if (!destination) throw std::bad_alloc(); |
| 363 | object = env_->CallStaticObjectMethod(engine_cls_, factory, destination, amount); |
| 364 | if (env_->ExceptionCheck() || !object) throw std::runtime_error("Could not create wallet transaction"); |
| 365 | env_->DeleteLocalRef(destination); |
| 366 | cls_ = env_->GetObjectClass(object); |
| 367 | } |
| 368 | void text(const char *name, const std::string &value) { |
| 369 | auto field = env_->GetFieldID(cls_, name, "Ljava/lang/String;"); |
| 370 | if (!field) throw std::runtime_error("Could not resolve transaction field"); |
| 371 | auto str = env_->NewStringUTF(value.c_str()); |
| 372 | if (!str) throw std::bad_alloc(); |
| 373 | env_->SetObjectField(object, field, str); |
| 374 | env_->DeleteLocalRef(str); |
| 375 | } |
| 376 | void number(const char *name, jlong value) { |
| 377 | auto field = env_->GetFieldID(cls_, name, "J"); |
| 378 | if (!field) throw std::runtime_error("Could not resolve transaction field"); |
| 379 | env_->SetLongField(object, field, value); |
| 380 | } |
| 381 | void boolean(const char *name, bool value) { |
| 382 | auto field = env_->GetFieldID(cls_, name, "Z"); |
| 383 | if (!field) throw std::runtime_error("Could not resolve transaction field"); |
| 384 | env_->SetBooleanField(object, field, value); |
| 385 | } |
| 386 | void phase(we::SendPhase value) { |
| 387 | auto setter = env_->GetStaticMethodID(engine_cls_, "setTransactionPhase", |
| 388 | "(Lorg/telegram/tgnet/tl/TL_wallet$walletTransaction;I)V"); |
| 389 | if (!setter) throw std::runtime_error("Could not resolve transaction phase"); |
| 390 | env_->CallStaticVoidMethod(engine_cls_, setter, object, static_cast<jint>(value)); |
| 391 | if (env_->ExceptionCheck()) throw std::runtime_error("Could not convert transaction phase"); |
| 392 | } |
| 393 | }; |
| 394 |
| 395 | jobject preview_transaction(JNIEnv *env, const we::SendPreview &preview, |
| 396 | const std::string &destination, jlong amount) { |
| 397 | Transaction result(env, destination, amount); |
| 398 | result.boolean("preview", true); |
| 399 | const auto &decimal_fee = preview.emulation.wallet_fees_nanograms; |
| 400 | jlong fee = 0; |
| 401 | const auto parsed = std::from_chars(decimal_fee.data(), decimal_fee.data() + decimal_fee.size(), fee); |
| 402 | if (parsed.ec != std::errc() || parsed.ptr != decimal_fee.data() + decimal_fee.size() || fee < 0) |
| 403 | throw std::runtime_error("Estimated fee exceeds the supported range"); |
| 404 | result.number("fee", fee); |
| 405 | result.text("traceFeesNanograms", preview.emulation.trace_fees_nanograms); |
| 406 | result.number("validUntil", static_cast<jlong>(preview.valid_until)); |
| 407 | result.boolean("traceSucceeded", preview.emulation.trace_succeeded); |
| 408 | result.boolean("traceIncomplete", preview.emulation.is_incomplete); |
| 409 | result.phase(we::SendPhase::kIdle); |
| 410 | return result.object; |
| 411 | } |
| 412 |
| 413 | class SecretScope { |
| 414 | std::shared_ptr<WalletHosts> hosts_; |
| 415 | public: |
| 416 | SecretScope(const Client &client, const SensitiveString &phrase, we::SecretAccessReason reason) |
| 417 | : hosts_(client.hosts) { |
| 418 | hosts_->secret = &phrase; |
| 419 | hosts_->secret_reason = reason; |
| 420 | } |
| 421 | ~SecretScope() { |
| 422 | hosts_->secret = nullptr; |
| 423 | hosts_->secret_reason = we::SecretAccessReason::kSignTransfer; |
| 424 | } |
| 425 | }; |
| 426 |
| 427 | class SendScope { |
| 428 | JNIEnv *env_; |
| 429 | std::shared_ptr<WalletHosts> hosts_; |
| 430 | jobject callback_ = nullptr; |
| 431 | public: |
| 432 | SendScope(JNIEnv *env, const Client &client, const SensitiveString &phrase, |
| 433 | jobject callback, const std::string &operation_id, |
| 434 | we::SecretAccessReason reason = we::SecretAccessReason::kSignTransfer) |
| 435 | : env_(env), hosts_(client.hosts) { |
| 436 | JavaVM *vm = nullptr; |
| 437 | env->GetJavaVM(&vm); |
| 438 | auto cls = env->GetObjectClass(callback); |
| 439 | auto state = env->GetMethodID(cls, "state", "(ILjava/lang/String;Ljava/lang/String;)V"); |
| 440 | env->DeleteLocalRef(cls); |
| 441 | if (!state) throw std::runtime_error("Could not resolve send callback"); |
| 442 | callback_ = env->NewGlobalRef(callback); |
| 443 | if (!callback_) throw std::bad_alloc(); |
| 444 | try { |
| 445 | hosts_->on_state = [vm, ref = callback_, state, operation_id](const we::SendSnapshot &snapshot) { |
| 446 | if (!snapshot.operation_id || *snapshot.operation_id != operation_id) return; |
| 447 | JavaEnv java(vm); |
| 448 | auto error = snapshot.error_message ? java.env->NewStringUTF(snapshot.error_message->c_str()) : nullptr; |
| 449 | auto transaction_hash = snapshot.resolution && snapshot.resolution->transaction_hash |
| 450 | ? java.env->NewStringUTF(snapshot.resolution->transaction_hash->c_str()) : nullptr; |
| 451 | if (!java.env->ExceptionCheck()) |
| 452 | java.env->CallVoidMethod(ref, state, static_cast<jint>(snapshot.phase), error, transaction_hash); |
| 453 | // UI delivery cannot change whether a signed transfer was submitted. |
| 454 | if (java.env->ExceptionCheck()) java.env->ExceptionClear(); |
| 455 | }; |
| 456 | } catch (...) { |
| 457 | env->DeleteGlobalRef(callback_); |
| 458 | throw; |
| 459 | } |
| 460 | hosts_->secret = &phrase; |
| 461 | hosts_->secret_reason = reason; |
| 462 | } |
| 463 | ~SendScope() { |
| 464 | hosts_->secret = nullptr; |
| 465 | hosts_->secret_reason = we::SecretAccessReason::kSignTransfer; |
| 466 | try { hosts_->report_state(); } catch (...) { } |
| 467 | hosts_->on_state = nullptr; |
| 468 | env_->DeleteGlobalRef(callback_); |
| 469 | } |
| 470 | }; |
| 471 |
| 472 | void throw_java(JNIEnv *env, const char *type, const char *message) { |
| 473 | if (env->ExceptionCheck()) return; |
| 474 | jclass cls = env->FindClass(type); |
| 475 | if (cls) { |
| 476 | env->ThrowNew(cls, message); |
| 477 | env->DeleteLocalRef(cls); |
| 478 | } |
| 479 | } |
| 480 | } // namespace |
| 481 |
| 482 | extern "C" JNIEXPORT jobjectArray JNICALL |
| 483 | Java_org_telegram_ui_Wallet_WalletEngine2_mnemonicWordlist(JNIEnv *env, jclass) { |
| 484 | try { |
| 485 | const auto words = we::mnemonic_wordlist(); |
| 486 | jclass string_class = env->FindClass("java/lang/String"); |
| 487 | if (!string_class) return nullptr; |
| 488 | jobjectArray result = env->NewObjectArray(static_cast<jsize>(words.size()), string_class, nullptr); |
| 489 | env->DeleteLocalRef(string_class); |
| 490 | if (!result) return nullptr; |
| 491 | for (size_t i = 0; i < words.size(); ++i) { |
| 492 | jstring word = env->NewStringUTF(words[i].c_str()); |
| 493 | if (!word) return nullptr; |
| 494 | env->SetObjectArrayElement(result, static_cast<jsize>(i), word); |
| 495 | env->DeleteLocalRef(word); |
| 496 | if (env->ExceptionCheck()) return nullptr; |
| 497 | } |
| 498 | return result; |
| 499 | } catch (const std::bad_alloc &) { |
| 500 | throw_java(env, "java/lang/OutOfMemoryError", "Could not load mnemonic word list"); |
| 501 | } catch (...) { |
| 502 | throw_java(env, "java/lang/IllegalStateException", "Could not load mnemonic word list"); |
| 503 | } |
| 504 | return nullptr; |
| 505 | } |
| 506 |
| 507 | extern "C" JNIEXPORT jbyteArray JNICALL |
| 508 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeSecretPhraseToPublicKey( |
| 509 | JNIEnv *env, jclass, jbyteArray secret_phrase) { |
| 510 | if (!secret_phrase) { |
| 511 | throw_java(env, "java/lang/IllegalArgumentException", "Recovery phrase is required"); |
| 512 | return nullptr; |
| 513 | } |
| 514 | try { |
| 515 | const jsize length = env->GetArrayLength(secret_phrase); |
| 516 | SensitiveString phrase(static_cast<size_t>(length)); |
| 517 | env->GetByteArrayRegion(secret_phrase, 0, length, reinterpret_cast<jbyte *>(phrase.value.data())); |
| 518 | if (env->ExceptionCheck()) return nullptr; |
| 519 | auto key = we::rotation_mnemonic_public_key(phrase.value); |
| 520 | ImportProofRequest parsed(phrase.value); |
| 521 | if (parsed.value.recovery_words.size() == 24) { |
| 522 | SensitiveString signing_phrase(0); |
| 523 | signing_phrase.value.reserve(phrase.value.size()); |
| 524 | for (size_t i = 12; i < 24; ++i) { |
| 525 | if (i != 12) signing_phrase.value.push_back(' '); |
| 526 | signing_phrase.value.append(parsed.value.recovery_words[i]); |
| 527 | } |
| 528 | key = we::rotation_mnemonic_public_key(signing_phrase.value); |
| 529 | } |
| 530 | if (key.size() != 32) throw std::runtime_error("Unexpected public key size"); |
| 531 | jbyteArray result = env->NewByteArray(32); |
| 532 | if (result) env->SetByteArrayRegion(result, 0, 32, reinterpret_cast<const jbyte *>(key.data())); |
| 533 | return result; |
| 534 | } catch (const we::WalletLifecycleError &) { |
| 535 | throw_java(env, "java/lang/IllegalArgumentException", "Invalid Rotation recovery phrase"); |
| 536 | } catch (const std::bad_alloc &) { |
| 537 | throw_java(env, "java/lang/OutOfMemoryError", "Could not derive wallet public key"); |
| 538 | } catch (...) { |
| 539 | throw_java(env, "java/lang/IllegalStateException", "Could not derive wallet public key"); |
| 540 | } |
| 541 | return nullptr; |
| 542 | } |
| 543 |
| 544 | extern "C" JNIEXPORT jstring JNICALL |
| 545 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeSecretPhraseToAddress( |
| 546 | JNIEnv *env, jclass, jbyteArray secret_phrase) { |
| 547 | if (!secret_phrase) { |
| 548 | throw_java(env, "java/lang/IllegalArgumentException", "Recovery phrase is required"); |
| 549 | return nullptr; |
| 550 | } |
| 551 | try { |
| 552 | const jsize length = env->GetArrayLength(secret_phrase); |
| 553 | SensitiveString phrase(static_cast<size_t>(length)); |
| 554 | env->GetByteArrayRegion(secret_phrase, 0, length, reinterpret_cast<jbyte *>(phrase.value.data())); |
| 555 | if (env->ExceptionCheck()) return nullptr; |
| 556 | // Reuse import's complete mnemonic validation and canonical address derivation. |
| 557 | // The host retains the phrase only for this call and wipes it on destruction. |
| 558 | ImportProofRequest request(phrase.value); |
| 559 | auto host = std::make_shared<EphemeralWalletHost>(we::SecretAccessReason::kSignTonConnectProof); |
| 560 | auto lifecycle = we::WalletLifecycle::init(host); |
| 561 | auto descriptor = lifecycle->import_wallet(request.value); |
| 562 | return env->NewStringUTF(descriptor.address.c_str()); |
| 563 | } catch (const we::wallet_lifecycle_error::InvalidRecoveryPhrase &) { |
| 564 | throw_java(env, "java/lang/IllegalArgumentException", "Invalid Rotation recovery phrase"); |
| 565 | } catch (const std::bad_alloc &) { |
| 566 | throw_java(env, "java/lang/OutOfMemoryError", "Could not derive wallet address"); |
| 567 | } catch (...) { |
| 568 | // Never include phrase contents in errors or logs. |
| 569 | throw_java(env, "java/lang/IllegalStateException", "Could not derive wallet address"); |
| 570 | } |
| 571 | return nullptr; |
| 572 | } |
| 573 |
| 574 | extern "C" JNIEXPORT jboolean JNICALL |
| 575 | Java_org_telegram_ui_Wallet_WalletEngine2_isValidCellBoc(JNIEnv *env, jclass, jstring boc) { |
| 576 | try { |
| 577 | return boc && gram_adapter::is_valid_cell_boc(java_string(env, boc)) ? JNI_TRUE : JNI_FALSE; |
| 578 | } catch (...) { |
| 579 | return JNI_FALSE; |
| 580 | } |
| 581 | } |
| 582 |
| 583 | extern "C" JNIEXPORT jbyteArray JNICALL |
| 584 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeTonConnectCrypto( |
| 585 | JNIEnv *env, jclass, jbyteArray phrase_bytes, jbyteArray parameters_bytes) { |
| 586 | if (!phrase_bytes || !parameters_bytes) { |
| 587 | throw_java(env, "java/lang/IllegalArgumentException", "Missing TON Connect approval data"); |
| 588 | return nullptr; |
| 589 | } |
| 590 | try { |
| 591 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 592 | SensitiveString parameters(static_cast<size_t>(env->GetArrayLength(parameters_bytes))); |
| 593 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 594 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 595 | if (env->ExceptionCheck()) return nullptr; |
| 596 | env->GetByteArrayRegion(parameters_bytes, 0, static_cast<jsize>(parameters.value.size()), |
| 597 | reinterpret_cast<jbyte *>(parameters.value.data())); |
| 598 | if (env->ExceptionCheck()) return nullptr; |
| 599 | SensitiveString output(0); |
| 600 | output.value = gram_adapter::ton_connect_crypto(phrase.value, parameters.value); |
| 601 | auto result = env->NewByteArray(static_cast<jsize>(output.value.size())); |
| 602 | if (result) env->SetByteArrayRegion(result, 0, static_cast<jsize>(output.value.size()), |
| 603 | reinterpret_cast<const jbyte *>(output.value.data())); |
| 604 | return result; |
| 605 | } catch (const std::invalid_argument &error) { |
| 606 | throw_java(env, "java/lang/IllegalArgumentException", error.what()); |
| 607 | } catch (const std::bad_alloc &) { |
| 608 | throw_java(env, "java/lang/OutOfMemoryError", "Could not prepare TON Connect approval"); |
| 609 | } catch (const std::exception &error) { |
| 610 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 611 | } catch (...) { |
| 612 | throw_java(env, "java/lang/IllegalStateException", "Could not prepare TON Connect approval"); |
| 613 | } |
| 614 | return nullptr; |
| 615 | } |
| 616 |
| 617 | extern "C" JNIEXPORT jobject JNICALL |
| 618 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeCreateImportProof( |
| 619 | JNIEnv *env, jclass, jbyteArray phrase_bytes, jbyteArray domain_bytes, |
| 620 | jbyteArray payload_bytes, jint timestamp, jboolean for_import) { |
| 621 | if (!phrase_bytes || !domain_bytes || !payload_bytes || timestamp <= 0 |
| 622 | || env->GetArrayLength(phrase_bytes) == 0 |
| 623 | || env->GetArrayLength(domain_bytes) == 0 |
| 624 | || env->GetArrayLength(payload_bytes) == 0) { |
| 625 | throw_java(env, "java/lang/IllegalArgumentException", "Recovery phrase and proof challenge are required"); |
| 626 | return nullptr; |
| 627 | } |
| 628 | try { |
| 629 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 630 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 631 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 632 | if (env->ExceptionCheck()) return nullptr; |
| 633 | // Use standard UTF-8 bytes, not JNI's modified UTF-8, for signed fields. |
| 634 | std::string domain(static_cast<size_t>(env->GetArrayLength(domain_bytes)), '\0'); |
| 635 | std::string payload(static_cast<size_t>(env->GetArrayLength(payload_bytes)), '\0'); |
| 636 | env->GetByteArrayRegion(domain_bytes, 0, static_cast<jsize>(domain.size()), |
| 637 | reinterpret_cast<jbyte *>(domain.data())); |
| 638 | if (env->ExceptionCheck()) return nullptr; |
| 639 | env->GetByteArrayRegion(payload_bytes, 0, static_cast<jsize>(payload.size()), |
| 640 | reinterpret_cast<jbyte *>(payload.data())); |
| 641 | if (env->ExceptionCheck()) return nullptr; |
| 642 |
| 643 | ImportProofRequest request(phrase.value); |
| 644 | auto host = std::make_shared<EphemeralWalletHost>(we::SecretAccessReason::kSignTonConnectProof); |
| 645 | auto lifecycle = we::WalletLifecycle::init(host); |
| 646 | auto descriptor = lifecycle->import_wallet(request.value); |
| 647 | if (for_import && request.value.recovery_words.size() == 24) { |
| 648 | // The complete phrase was validated above. MTProto import verifies |
| 649 | // with the submitted address-derivation key, not the rotated key. |
| 650 | // Importing its first half retains the same address and authorizes |
| 651 | // that key for this one proof. Wipe discarded signing words first. |
| 652 | for (size_t i = 12; i < request.value.recovery_words.size(); ++i) { |
| 653 | auto &word = request.value.recovery_words[i]; |
| 654 | volatile char *data = word.data(); |
| 655 | for (size_t j = 0; j < word.size(); ++j) data[j] = 0; |
| 656 | } |
| 657 | request.value.recovery_words.resize(12); |
| 658 | host = std::make_shared<EphemeralWalletHost>(we::SecretAccessReason::kSignTonConnectProof); |
| 659 | lifecycle = we::WalletLifecycle::init(host); |
| 660 | descriptor = lifecycle->import_wallet(request.value); |
| 661 | } |
| 662 | auto proof = lifecycle->sign_ton_connect_proof({descriptor, domain, |
| 663 | static_cast<uint64_t>(timestamp), payload}); |
| 664 | if (descriptor.public_key.size() != 32 || proof.signature.size() != 64) |
| 665 | throw std::runtime_error("Unexpected ownership proof size"); |
| 666 |
| 667 | auto cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$ImportedWalletProof"); |
| 668 | if (!cls) return nullptr; |
| 669 | auto constructor = env->GetMethodID(cls, "<init>", "([BI[B)V"); |
| 670 | if (!constructor) return nullptr; |
| 671 | auto public_key = env->NewByteArray(32); |
| 672 | if (!public_key) return nullptr; |
| 673 | auto signature = env->NewByteArray(64); |
| 674 | if (!signature) return nullptr; |
| 675 | // MTProto import derives the address and verifies the proof with this |
| 676 | // same anchor key. Other ownership proofs retain current-key signing. |
| 677 | env->SetByteArrayRegion(public_key, 0, 32, |
| 678 | reinterpret_cast<const jbyte *>(descriptor.public_key.data())); |
| 679 | if (env->ExceptionCheck()) return nullptr; |
| 680 | env->SetByteArrayRegion(signature, 0, 64, |
| 681 | reinterpret_cast<const jbyte *>(proof.signature.data())); |
| 682 | if (env->ExceptionCheck()) return nullptr; |
| 683 | return env->NewObject(cls, constructor, public_key, timestamp, signature); |
| 684 | } catch (const we::wallet_lifecycle_error::InvalidRecoveryPhrase &) { |
| 685 | throw_java(env, "java/lang/IllegalArgumentException", "Invalid Rotation recovery phrase"); |
| 686 | } catch (const std::bad_alloc &) { |
| 687 | throw_java(env, "java/lang/OutOfMemoryError", "Could not create wallet ownership proof"); |
| 688 | } catch (...) { |
| 689 | // Never include phrase contents in errors or logs. |
| 690 | throw_java(env, "java/lang/IllegalStateException", "Could not create wallet ownership proof"); |
| 691 | } |
| 692 | return nullptr; |
| 693 | } |
| 694 |
| 695 | extern "C" JNIEXPORT jboolean JNICALL |
| 696 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeIsValidAddress( |
| 697 | JNIEnv *env, jclass, jstring address) { |
| 698 | if (!address) return JNI_FALSE; |
| 699 | try { |
| 700 | const auto value = java_string(env, address); |
| 701 | // TON addresses are ASCII; reject JNI modified UTF-8 before passing it to Rust. |
| 702 | for (unsigned char c : value) { |
| 703 | if (c >= 0x80) return JNI_FALSE; |
| 704 | } |
| 705 | return we::is_valid_ton_address(value) ? JNI_TRUE : JNI_FALSE; |
| 706 | } catch (const std::bad_alloc &) { |
| 707 | throw_java(env, "java/lang/OutOfMemoryError", "Could not validate TON address"); |
| 708 | } catch (...) { |
| 709 | throw_java(env, "java/lang/IllegalStateException", "Could not validate TON address"); |
| 710 | } |
| 711 | return JNI_FALSE; |
| 712 | } |
| 713 |
| 714 | extern "C" JNIEXPORT jstring JNICALL |
| 715 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeTransactionAddress( |
| 716 | JNIEnv *env, jclass, jstring address) { |
| 717 | try { |
| 718 | const auto friendly = we::convert_ton_address( |
| 719 | java_string(env, address), we::TonAddressFormat::kUserFriendly{false, false}); |
| 720 | return env->NewStringUTF(friendly.c_str()); |
| 721 | } catch (const std::bad_alloc &) { |
| 722 | throw_java(env, "java/lang/OutOfMemoryError", "Could not format transaction address"); |
| 723 | } catch (...) { |
| 724 | throw_java(env, "java/lang/IllegalArgumentException", "Invalid transaction address"); |
| 725 | } |
| 726 | return nullptr; |
| 727 | } |
| 728 |
| 729 | extern "C" JNIEXPORT jlong JNICALL |
| 730 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeCreate( |
| 731 | JNIEnv *env, jclass, jint current_account, jstring address, jbyteArray public_key, jobject transport, jstring journal_directory) { |
| 732 | try { |
| 733 | if (!address || !public_key || env->GetArrayLength(public_key) != 32) { |
| 734 | throw std::invalid_argument("Wallet address and a 32-byte public key are required"); |
| 735 | } |
| 736 | const char *chars = env->GetStringUTFChars(address, nullptr); |
| 737 | if (!chars) return 0; |
| 738 | std::string wallet_address; |
| 739 | try { |
| 740 | wallet_address = chars; |
| 741 | } catch (...) { |
| 742 | env->ReleaseStringUTFChars(address, chars); |
| 743 | throw; |
| 744 | } |
| 745 | env->ReleaseStringUTFChars(address, chars); |
| 746 |
| 747 | const auto raw_address = we::convert_ton_address(wallet_address, we::TonAddressFormat::kRaw{}); |
| 748 | std::vector<uint8_t> key(32); |
| 749 | env->GetByteArrayRegion(public_key, 0, 32, reinterpret_cast<jbyte *>(key.data())); |
| 750 | if (env->ExceptionCheck()) return 0; |
| 751 |
| 752 | const auto record_id = "telegram-" + std::to_string(current_account) + ":" + raw_address; |
| 753 | we::WalletClientConfig config{ |
| 754 | record_id, |
| 755 | wallet_address, |
| 756 | std::move(key), |
| 757 | we::ProtectedSecretRef{record_id + ":mnemonic"}, |
| 758 | we::Network::kMainnet, |
| 759 | 60, |
| 760 | 30, |
| 761 | we::ProviderConfig{"https://toncenter.com", std::nullopt, 15000} |
| 762 | }; |
| 763 | auto hosts = std::make_shared<WalletHosts>(env, transport, java_string(env, journal_directory)); |
| 764 | hosts->secret_ref = record_id + ":mnemonic"; |
| 765 | auto client = we::WalletClient::new_statusless(config, hosts, hosts); |
| 766 | hosts->client = client; |
| 767 |
| 768 | std::lock_guard<std::mutex> lock(clients_mutex); |
| 769 | if (next_handle == std::numeric_limits<jlong>::max()) { |
| 770 | throw std::runtime_error("Wallet engine handles exhausted"); |
| 771 | } |
| 772 | const jlong handle = next_handle++; |
| 773 | clients.emplace(handle, Client{std::move(client), std::move(hosts)}); |
| 774 | return handle; |
| 775 | } catch (const std::bad_alloc &) { |
| 776 | throw_java(env, "java/lang/OutOfMemoryError", "Could not initialize wallet engine"); |
| 777 | } catch (const std::exception &error) { |
| 778 | throw_java(env, "java/lang/IllegalArgumentException", error.what()); |
| 779 | } catch (...) { |
| 780 | throw_java(env, "java/lang/IllegalStateException", "Could not initialize wallet engine"); |
| 781 | } |
| 782 | return 0; |
| 783 | } |
| 784 |
| 785 | extern "C" JNIEXPORT jlong JNICALL |
| 786 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeBalance(JNIEnv *env, jclass, jlong handle) { |
| 787 | try { |
| 788 | std::shared_ptr<we::WalletClient> client; |
| 789 | { |
| 790 | std::lock_guard<std::mutex> lock(clients_mutex); |
| 791 | auto it = clients.find(handle); |
| 792 | if (it == clients.end()) throw std::runtime_error("Wallet engine is closed"); |
| 793 | client = it->second.wallet; |
| 794 | } |
| 795 | const auto update = client->refresh(); |
| 796 | const auto &snapshot = update.snapshot; |
| 797 | if (snapshot.account_resource.phase != we::ResourcePhase::kReady || !snapshot.account) { |
| 798 | throw std::runtime_error(snapshot.account_resource.error |
| 799 | ? snapshot.account_resource.error->developer_message : "Could not load wallet balance"); |
| 800 | } |
| 801 | const auto &decimal = snapshot.account->balance_nanograms; |
| 802 | jlong balance = 0; |
| 803 | const auto parsed = std::from_chars(decimal.data(), decimal.data() + decimal.size(), balance); |
| 804 | if (parsed.ec != std::errc() || parsed.ptr != decimal.data() + decimal.size() || balance < 0) |
| 805 | throw std::runtime_error("Wallet balance exceeds the supported range"); |
| 806 | return balance; |
| 807 | } catch (const std::bad_alloc &) { |
| 808 | throw_java(env, "java/lang/OutOfMemoryError", "Could not load wallet balance"); |
| 809 | } catch (const std::exception &error) { |
| 810 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 811 | } catch (...) { |
| 812 | throw_java(env, "java/lang/IllegalStateException", "Could not load wallet balance"); |
| 813 | } |
| 814 | return 0; |
| 815 | } |
| 816 |
| 817 | extern "C" JNIEXPORT jobject JNICALL |
| 818 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeEmulateSend( |
| 819 | JNIEnv *env, jclass, jlong handle, jstring address, jlong amount, |
| 820 | jbyteArray comment_bytes, jboolean comment_encrypted) { |
| 821 | try { |
| 822 | auto client = get_client(handle); |
| 823 | auto destination = java_string(env, address); |
| 824 | auto body = we::SendMessageBody(we::SendMessageBody::kEmpty{}); |
| 825 | if (comment_bytes) { |
| 826 | std::string comment(static_cast<size_t>(env->GetArrayLength(comment_bytes)), '\0'); |
| 827 | env->GetByteArrayRegion(comment_bytes, 0, static_cast<jsize>(comment.size()), |
| 828 | reinterpret_cast<jbyte *>(comment.data())); |
| 829 | if (env->ExceptionCheck()) return nullptr; |
| 830 | // For encrypted previews Java supplies a size-matched placeholder BOC. |
| 831 | body = comment_encrypted |
| 832 | ? we::SendMessageBody(we::SendMessageBody::kRawPayload{comment}) |
| 833 | : we::SendMessageBody(we::SendMessageBody::kComment{comment}); |
| 834 | } |
| 835 | auto preview = client.wallet->preview_send({transfer_intent(destination, amount, std::move(body))}); |
| 836 | return preview_transaction(env, preview, destination, amount); |
| 837 | } catch (const std::bad_alloc &) { |
| 838 | throw_java(env, "java/lang/OutOfMemoryError", "Could not preview transfer"); |
| 839 | } catch (const std::exception &error) { |
| 840 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 841 | } catch (...) { |
| 842 | throw_java(env, "java/lang/IllegalStateException", "Could not preview transfer"); |
| 843 | } |
| 844 | return nullptr; |
| 845 | } |
| 846 |
| 847 | extern "C" JNIEXPORT jobject JNICALL |
| 848 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeEmulateRotateKey( |
| 849 | JNIEnv *env, jclass, jlong handle, jstring address) { |
| 850 | try { |
| 851 | // No SecretScope: preview_key_rotation accepts public state only and |
| 852 | // constructs zero owner/proof signatures before contacting Toncenter. |
| 853 | const auto preview = get_client(handle).wallet->preview_key_rotation(); |
| 854 | return preview_transaction(env, preview, java_string(env, address), 0); |
| 855 | } catch (const std::bad_alloc &) { |
| 856 | throw_java(env, "java/lang/OutOfMemoryError", "Could not emulate key rotation"); |
| 857 | } catch (const std::exception &error) { |
| 858 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 859 | } catch (...) { |
| 860 | throw_java(env, "java/lang/IllegalStateException", "Could not emulate key rotation"); |
| 861 | } |
| 862 | return nullptr; |
| 863 | } |
| 864 |
| 865 | extern "C" JNIEXPORT jobject JNICALL |
| 866 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePrepareRotateKey( |
| 867 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jstring gasless_address) { |
| 868 | try { |
| 869 | auto client = get_client(handle); |
| 870 | if (!phrase_bytes || env->GetArrayLength(phrase_bytes) == 0) |
| 871 | throw std::invalid_argument("Recovery phrase is required"); |
| 872 | if (gasless_address && !we::is_valid_ton_address(java_string(env, gasless_address))) |
| 873 | throw std::invalid_argument("Valid relayer address is required"); |
| 874 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 875 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 876 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 877 | if (env->ExceptionCheck()) return nullptr; |
| 878 | SecretScope scope(client, phrase, we::SecretAccessReason::kPrepareKeyRotation); |
| 879 | const auto snapshot = client.wallet->refresh().snapshot; |
| 880 | if (snapshot.account_resource.phase != we::ResourcePhase::kReady || !snapshot.account) |
| 881 | throw std::runtime_error(snapshot.account_resource.error |
| 882 | ? snapshot.account_resource.error->developer_message : "Could not load wallet account"); |
| 883 | constexpr uint64_t validity_seconds = 120; |
| 884 | if (snapshot.account->sync_utime > std::numeric_limits<uint32_t>::max() - validity_seconds) |
| 885 | throw std::runtime_error("Key rotation expiration exceeds the supported range"); |
| 886 | auto prepared = client.wallet->prepare_key_rotation({ |
| 887 | snapshot.account->sync_utime + validity_seconds, we::KeyRotationMessageKind::kExternal}); |
| 888 | SensitiveString replacement(0); |
| 889 | replacement.value.swap(prepared.replacement_recovery_phrase.phrase); |
| 890 | if (prepared.new_public_key.size() != 32) |
| 891 | throw std::runtime_error("Unexpected signing public key size"); |
| 892 | const auto cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$PreparedRotation"); |
| 893 | if (!cls) return nullptr; |
| 894 | const auto constructor = env->GetMethodID(cls, "<init>", |
| 895 | "(Ljava/lang/String;Ljava/lang/String;[B[B)V"); |
| 896 | if (!constructor) return nullptr; |
| 897 | const auto external = env->NewStringUTF(prepared.external_boc.c_str()); |
| 898 | if (!external) return nullptr; |
| 899 | const auto internal = gasless_address ? env->NewStringUTF(prepared.internal_boc.c_str()) : nullptr; |
| 900 | if (env->ExceptionCheck()) return nullptr; |
| 901 | const auto public_key = env->NewByteArray(32); |
| 902 | if (!public_key) return nullptr; |
| 903 | env->SetByteArrayRegion(public_key, 0, 32, |
| 904 | reinterpret_cast<const jbyte *>(prepared.new_public_key.data())); |
| 905 | if (env->ExceptionCheck()) return nullptr; |
| 906 | const auto bytes = env->NewByteArray(static_cast<jsize>(replacement.value.size())); |
| 907 | if (!bytes) return nullptr; |
| 908 | env->SetByteArrayRegion(bytes, 0, static_cast<jsize>(replacement.value.size()), |
| 909 | reinterpret_cast<const jbyte *>(replacement.value.data())); |
| 910 | if (env->ExceptionCheck()) return nullptr; |
| 911 | // The Java constructor clears its phrase bytes after creating the result. |
| 912 | return env->NewObject(cls, constructor, external, internal, bytes, public_key); |
| 913 | } catch (const std::bad_alloc &) { |
| 914 | throw_java(env, "java/lang/OutOfMemoryError", "Could not prepare key rotation"); |
| 915 | } catch (const std::exception &error) { |
| 916 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 917 | } catch (...) { |
| 918 | throw_java(env, "java/lang/IllegalStateException", "Could not prepare key rotation"); |
| 919 | } |
| 920 | return nullptr; |
| 921 | } |
| 922 |
| 923 | extern "C" JNIEXPORT jbyteArray JNICALL |
| 924 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeDecryptRawComment( |
| 925 | JNIEnv *env, jclass, jbyteArray phrase_bytes, jstring sender, jstring body) { |
| 926 | if (!phrase_bytes || !sender || !body || env->GetArrayLength(phrase_bytes) == 0) { |
| 927 | throw_java(env, "java/lang/IllegalArgumentException", "Recovery phrase, sender and message body are required"); |
| 928 | return nullptr; |
| 929 | } |
| 930 | try { |
| 931 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 932 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 933 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 934 | if (env->ExceptionCheck()) return nullptr; |
| 935 | ImportProofRequest request(phrase.value); |
| 936 | auto host = std::make_shared<EphemeralWalletHost>(we::SecretAccessReason::kDecryptComment); |
| 937 | auto lifecycle = we::WalletLifecycle::init(host); |
| 938 | auto descriptor = lifecycle->import_wallet(request.value); |
| 939 | we::WalletClientConfig config{ |
| 940 | descriptor.record_id, descriptor.address, descriptor.public_key, |
| 941 | descriptor.secret_ref, descriptor.network, 60, 30, |
| 942 | we::ProviderConfig{"https://toncenter.com", std::nullopt, 15000} |
| 943 | }; |
| 944 | // The existing engine API takes a client, but decryption uses only local |
| 945 | // key material. A dedicated transport prohibits any provider requests. |
| 946 | auto client = we::WalletClient::new_statusless(config, |
| 947 | std::make_shared<OfflineWalletTransport>(), host); |
| 948 | SensitiveString plaintext(0); |
| 949 | plaintext.value = client->decrypt_comment({java_string(env, sender), java_string(env, body)}); |
| 950 | auto result = env->NewByteArray(static_cast<jsize>(plaintext.value.size())); |
| 951 | if (!result) return nullptr; |
| 952 | env->SetByteArrayRegion(result, 0, static_cast<jsize>(plaintext.value.size()), |
| 953 | reinterpret_cast<const jbyte *>(plaintext.value.data())); |
| 954 | return result; |
| 955 | } catch (const we::wallet_lifecycle_error::InvalidRecoveryPhrase &) { |
| 956 | throw_java(env, "java/lang/IllegalArgumentException", "Invalid Rotation recovery phrase"); |
| 957 | } catch (const std::bad_alloc &) { |
| 958 | throw_java(env, "java/lang/OutOfMemoryError", "Could not decrypt transaction comment"); |
| 959 | } catch (...) { |
| 960 | // Do not expose secret material or unauthenticated plaintext in diagnostics. |
| 961 | throw_java(env, "java/lang/IllegalStateException", "Could not decrypt transaction comment"); |
| 962 | } |
| 963 | return nullptr; |
| 964 | } |
| 965 |
| 966 | extern "C" JNIEXPORT jbyteArray JNICALL |
| 967 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeDecryptComment( |
| 968 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, |
| 969 | jstring sender, jstring body) { |
| 970 | try { |
| 971 | if (!phrase_bytes || !sender || !body) |
| 972 | throw std::invalid_argument("Recovery phrase, sender and message body are required"); |
| 973 | auto client = get_client(handle); |
| 974 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 975 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 976 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 977 | if (env->ExceptionCheck()) return nullptr; |
| 978 |
| 979 | SecretScope scope(client, phrase, we::SecretAccessReason::kDecryptComment); |
| 980 | const auto comment = client.wallet->decrypt_comment({ |
| 981 | java_string(env, sender), java_string(env, body)}); |
| 982 | auto result = env->NewByteArray(static_cast<jsize>(comment.size())); |
| 983 | if (!result) return nullptr; |
| 984 | env->SetByteArrayRegion(result, 0, static_cast<jsize>(comment.size()), |
| 985 | reinterpret_cast<const jbyte *>(comment.data())); |
| 986 | return result; |
| 987 | } catch (const std::bad_alloc &) { |
| 988 | throw_java(env, "java/lang/OutOfMemoryError", "Could not decrypt transaction comment"); |
| 989 | } catch (const std::exception &error) { |
| 990 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 991 | } catch (...) { |
| 992 | throw_java(env, "java/lang/IllegalStateException", "Could not decrypt transaction comment"); |
| 993 | } |
| 994 | return nullptr; |
| 995 | } |
| 996 |
| 997 | namespace { |
| 998 | we::SendIntent ton_connect_intent(JNIEnv *env, jobjectArray fields, jlong valid_until) { |
| 999 | const int count = fields ? env->GetArrayLength(fields) : 0; |
| 1000 | if (count == 0 || count % 5 || count > 255 * 5 || valid_until < 0) |
| 1001 | throw std::invalid_argument("Invalid TON Connect transaction"); |
| 1002 | we::SendIntent intent{valid_until == 0 ? we::SendExpiration(we::SendExpiration::kEngineDefault{}) |
| 1003 | : we::SendExpiration(we::SendExpiration::kExact{static_cast<uint64_t>(valid_until)}), {}}; |
| 1004 | for (int i = 0; i < count; i += 5) { |
| 1005 | std::optional<std::string> values[5]; |
| 1006 | for (int j = 0; j < 5; ++j) { |
| 1007 | auto value = static_cast<jstring>(env->GetObjectArrayElement(fields, i + j)); |
| 1008 | if (value) { values[j] = java_string(env, value); env->DeleteLocalRef(value); } |
| 1009 | } |
| 1010 | if (!values[0] || !values[1] || !values[4] || (*values[4] != "0" && *values[4] != "1")) throw std::invalid_argument("Missing transfer fields"); |
| 1011 | auto body = values[2] ? we::SendMessageBody(we::SendMessageBody::kRawPayload{*values[2]}) |
| 1012 | : we::SendMessageBody(we::SendMessageBody::kEmpty{}); |
| 1013 | intent.messages.push_back({*values[0], we::SendAmount::kExact{*values[1]}, body, *values[4] == "1", values[3]}); |
| 1014 | } |
| 1015 | return intent; |
| 1016 | } |
| 1017 | } |
| 1018 |
| 1019 | extern "C" JNIEXPORT jobject JNICALL |
| 1020 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePreviewTonConnect( |
| 1021 | JNIEnv *env, jclass, jlong handle, jobjectArray fields, jlong valid_until) { |
| 1022 | try { |
| 1023 | auto intent = ton_connect_intent(env, fields, valid_until); |
| 1024 | auto preview = get_client(handle).wallet->preview_ton_connect({"ton-connect-preview", false, intent}); |
| 1025 | return preview_transaction(env, preview, intent.messages.front().destination, 0); |
| 1026 | } catch (const std::exception &error) { |
| 1027 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1028 | } catch (...) { |
| 1029 | throw_java(env, "java/lang/IllegalStateException", "Could not preview TON Connect transaction"); |
| 1030 | } |
| 1031 | return nullptr; |
| 1032 | } |
| 1033 |
| 1034 | extern "C" JNIEXPORT void JNICALL |
| 1035 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePreviewSignMessage( |
| 1036 | JNIEnv *env, jclass, jlong handle, jobjectArray fields, jlong valid_until) { |
| 1037 | try { |
| 1038 | auto intent = ton_connect_intent(env, fields, valid_until); |
| 1039 | get_client(handle).wallet->preview_sign_message({intent}); |
| 1040 | } catch (const std::exception &error) { |
| 1041 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1042 | } catch (...) { |
| 1043 | throw_java(env, "java/lang/IllegalStateException", "Could not preview message signing"); |
| 1044 | } |
| 1045 | } |
| 1046 |
| 1047 | extern "C" JNIEXPORT jstring JNICALL |
| 1048 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeSignMessage( |
| 1049 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jobjectArray fields, |
| 1050 | jlong valid_until, jstring operation_id) { |
| 1051 | try { |
| 1052 | auto client = get_client(handle); |
| 1053 | auto intent = ton_connect_intent(env, fields, valid_until); |
| 1054 | if (!phrase_bytes) throw std::invalid_argument("Recovery phrase is required"); |
| 1055 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1056 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1057 | if (env->ExceptionCheck()) return nullptr; |
| 1058 | SecretScope scope(client, phrase, we::SecretAccessReason::kSignTransfer); |
| 1059 | // The engine journals the internal message before handoff and never broadcasts it. |
| 1060 | const auto signed_message = client.wallet->sign_message({java_string(env, operation_id), false, intent}); |
| 1061 | return env->NewStringUTF(signed_message.internal_boc.c_str()); |
| 1062 | } catch (const std::exception &error) { |
| 1063 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1064 | } catch (...) { |
| 1065 | throw_java(env, "java/lang/IllegalStateException", "Could not sign internal message"); |
| 1066 | } |
| 1067 | return nullptr; |
| 1068 | } |
| 1069 |
| 1070 | extern "C" JNIEXPORT jobject JNICALL |
| 1071 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePrepareTonConnectTransfer( |
| 1072 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jobjectArray fields, |
| 1073 | jlong valid_until, jstring operation_id) { |
| 1074 | try { |
| 1075 | auto client = get_client(handle); |
| 1076 | auto intent = ton_connect_intent(env, fields, valid_until); |
| 1077 | if (!phrase_bytes) throw std::invalid_argument("Recovery phrase is required"); |
| 1078 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1079 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1080 | if (env->ExceptionCheck()) return nullptr; |
| 1081 | SecretScope scope(client, phrase, we::SecretAccessReason::kSignTransfer); |
| 1082 | auto prepared = client.wallet->prepare_transfer({java_string(env, operation_id), intent}); |
| 1083 | auto cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$PreparedSend"); |
| 1084 | if (!cls) return nullptr; |
| 1085 | auto ctor = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); |
| 1086 | if (!ctor) return nullptr; |
| 1087 | return env->NewObject(cls, ctor, env->NewStringUTF(prepared.external_boc.c_str()), nullptr, nullptr); |
| 1088 | } catch (const std::exception &error) { |
| 1089 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1090 | } catch (...) { |
| 1091 | throw_java(env, "java/lang/IllegalStateException", "Could not prepare TON Connect transaction"); |
| 1092 | } |
| 1093 | return nullptr; |
| 1094 | } |
| 1095 |
| 1096 | extern "C" JNIEXPORT jobject JNICALL |
| 1097 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePrepareSend( |
| 1098 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jstring address, |
| 1099 | jlong amount, jbyteArray comment_bytes, jbyteArray comment_recipient_public_key, |
| 1100 | jstring gasless_address, jstring operation_id) { |
| 1101 | try { |
| 1102 | auto client = get_client(handle); |
| 1103 | const auto destination = java_string(env, address); |
| 1104 | if (!we::is_valid_ton_address(destination)) |
| 1105 | throw std::invalid_argument("Valid destination address is required"); |
| 1106 | std::optional<std::string> relayer; |
| 1107 | if (gasless_address) { |
| 1108 | relayer = java_string(env, gasless_address); |
| 1109 | if (!we::is_valid_ton_address(*relayer)) |
| 1110 | throw std::invalid_argument("Valid relayer address is required"); |
| 1111 | } |
| 1112 | if (amount < 0) throw std::invalid_argument("Transfer amount must not be negative"); |
| 1113 | if (!phrase_bytes) throw std::invalid_argument("Recovery phrase is required"); |
| 1114 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1115 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 1116 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1117 | if (env->ExceptionCheck()) return nullptr; |
| 1118 | std::optional<we::Boc> encrypted_comment_body; |
| 1119 | auto body = we::SendMessageBody(we::SendMessageBody::kEmpty{}); |
| 1120 | if (comment_bytes) { |
| 1121 | std::string comment(static_cast<size_t>(env->GetArrayLength(comment_bytes)), '\0'); |
| 1122 | env->GetByteArrayRegion(comment_bytes, 0, static_cast<jsize>(comment.size()), |
| 1123 | reinterpret_cast<jbyte *>(comment.data())); |
| 1124 | if (env->ExceptionCheck()) return nullptr; |
| 1125 | if (comment_recipient_public_key) { |
| 1126 | std::vector<uint8_t> recipient_key(static_cast<size_t>(env->GetArrayLength(comment_recipient_public_key))); |
| 1127 | if (recipient_key.size() != 32) throw std::invalid_argument("Recipient public key must be 32 bytes"); |
| 1128 | env->GetByteArrayRegion(comment_recipient_public_key, 0, 32, reinterpret_cast<jbyte *>(recipient_key.data())); |
| 1129 | if (env->ExceptionCheck()) return nullptr; |
| 1130 | SecretScope scope(client, phrase, we::SecretAccessReason::kEncryptComment); |
| 1131 | encrypted_comment_body = client.wallet->create_encrypted_comment({destination, comment, recipient_key}); |
| 1132 | body = we::SendMessageBody::kRawPayload{*encrypted_comment_body}; |
| 1133 | } else { |
| 1134 | body = we::SendMessageBody::kComment{comment}; |
| 1135 | } |
| 1136 | } |
| 1137 | SecretScope scope(client, phrase, we::SecretAccessReason::kSignTransfer); |
| 1138 | const auto prepared = client.wallet->prepare_transfer({ |
| 1139 | java_string(env, operation_id), transfer_intent(destination, amount, std::move(body))}); |
| 1140 | const auto external_boc = env->NewStringUTF(prepared.external_boc.c_str()); |
| 1141 | if (!external_boc) return nullptr; |
| 1142 | const auto internal_boc = relayer ? env->NewStringUTF(prepared.internal_boc.c_str()) : nullptr; |
| 1143 | if (env->ExceptionCheck()) return nullptr; |
| 1144 | const auto comment_body = encrypted_comment_body |
| 1145 | ? env->NewStringUTF(encrypted_comment_body->c_str()) : nullptr; |
| 1146 | if (env->ExceptionCheck()) return nullptr; |
| 1147 | const auto prepared_cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$PreparedSend"); |
| 1148 | if (!prepared_cls) return nullptr; |
| 1149 | const auto prepared_constructor = env->GetMethodID(prepared_cls, "<init>", |
| 1150 | "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); |
| 1151 | if (!prepared_constructor) return nullptr; |
| 1152 | return env->NewObject(prepared_cls, prepared_constructor, external_boc, internal_boc, comment_body); |
| 1153 | } catch (const std::bad_alloc &) { |
| 1154 | throw_java(env, "java/lang/OutOfMemoryError", "Could not prepare transfer"); |
| 1155 | } catch (const std::exception &error) { |
| 1156 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1157 | } catch (...) { |
| 1158 | throw_java(env, "java/lang/IllegalStateException", "Could not prepare transfer"); |
| 1159 | } |
| 1160 | return nullptr; |
| 1161 | } |
| 1162 |
| 1163 | extern "C" JNIEXPORT jstring JNICALL |
| 1164 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeMessageBodyHash( |
| 1165 | JNIEnv *env, jclass, jstring boc) { |
| 1166 | try { |
| 1167 | const auto hash = gram_adapter::message_body_hash(java_string(env, boc)); |
| 1168 | return env->NewStringUTF(hash.c_str()); |
| 1169 | } catch (const std::bad_alloc &) { |
| 1170 | throw_java(env, "java/lang/OutOfMemoryError", "Could not hash message body"); |
| 1171 | } catch (...) { |
| 1172 | throw_java(env, "java/lang/IllegalStateException", "Could not hash message body"); |
| 1173 | } |
| 1174 | return nullptr; |
| 1175 | } |
| 1176 |
| 1177 | extern "C" JNIEXPORT jobject JNICALL |
| 1178 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeSend( |
| 1179 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jstring address, |
| 1180 | jlong amount, jbyteArray comment_bytes, jbyteArray comment_recipient_public_key, |
| 1181 | jstring operation_id, jobject callbacks) { |
| 1182 | try { |
| 1183 | auto client = get_client(handle); |
| 1184 | auto destination = java_string(env, address); |
| 1185 | std::optional<std::string> comment; |
| 1186 | if (comment_bytes) { |
| 1187 | comment.emplace(static_cast<size_t>(env->GetArrayLength(comment_bytes)), '\0'); |
| 1188 | env->GetByteArrayRegion(comment_bytes, 0, static_cast<jsize>(comment->size()), |
| 1189 | reinterpret_cast<jbyte *>(comment->data())); |
| 1190 | if (env->ExceptionCheck()) return nullptr; |
| 1191 | } |
| 1192 | auto id = java_string(env, operation_id); |
| 1193 | if (!phrase_bytes || !callbacks) throw std::invalid_argument("Recovery phrase and callbacks are required"); |
| 1194 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1195 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 1196 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1197 | if (env->ExceptionCheck()) return nullptr; |
| 1198 | auto body = comment |
| 1199 | ? we::SendMessageBody(we::SendMessageBody::kComment{*comment}) |
| 1200 | : we::SendMessageBody(we::SendMessageBody::kEmpty{}); |
| 1201 | if (comment && comment_recipient_public_key) { |
| 1202 | std::vector<uint8_t> recipient_key(static_cast<size_t>(env->GetArrayLength(comment_recipient_public_key))); |
| 1203 | if (recipient_key.size() != 32) throw std::invalid_argument("Recipient public key must be 32 bytes"); |
| 1204 | env->GetByteArrayRegion(comment_recipient_public_key, 0, 32, reinterpret_cast<jbyte *>(recipient_key.data())); |
| 1205 | if (env->ExceptionCheck()) return nullptr; |
| 1206 | SecretScope scope(client, phrase, we::SecretAccessReason::kEncryptComment); |
| 1207 | body = we::SendMessageBody::kRawPayload{ |
| 1208 | client.wallet->create_encrypted_comment({destination, *comment, recipient_key}) |
| 1209 | }; |
| 1210 | } |
| 1211 | auto intent = transfer_intent(destination, amount, std::move(body)); |
| 1212 | SendScope scope(env, client, phrase, callbacks, id); |
| 1213 | auto sent = client.wallet->send({id, false, intent}); |
| 1214 | Transaction result(env, destination, amount); |
| 1215 | result.boolean("feeUnknown", true); |
| 1216 | result.text("operationId", sent.operation_id); |
| 1217 | result.text("messageHash", sent.message_hash); |
| 1218 | result.phase(sent.phase); |
| 1219 | return result.object; |
| 1220 | } catch (const std::bad_alloc &) { |
| 1221 | throw_java(env, "java/lang/OutOfMemoryError", "Could not send transfer"); |
| 1222 | } catch (const std::exception &error) { |
| 1223 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1224 | } catch (...) { |
| 1225 | throw_java(env, "java/lang/IllegalStateException", "Could not send transfer"); |
| 1226 | } |
| 1227 | return nullptr; |
| 1228 | } |
| 1229 |
| 1230 | extern "C" JNIEXPORT jobject JNICALL |
| 1231 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeResolvePending(JNIEnv *env, jclass, jlong handle) { |
| 1232 | try { |
| 1233 | const auto snapshot = get_client(handle).wallet->resolve_pending(); |
| 1234 | const auto cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$SendResolution"); |
| 1235 | if (!cls) return nullptr; |
| 1236 | const auto constructor = env->GetMethodID(cls, "<init>", |
| 1237 | "(Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;J)V"); |
| 1238 | if (!constructor) return nullptr; |
| 1239 | const auto operation_id = snapshot.operation_id ? env->NewStringUTF(snapshot.operation_id->c_str()) : nullptr; |
| 1240 | const auto transaction_hash = snapshot.resolution && snapshot.resolution->transaction_hash |
| 1241 | ? env->NewStringUTF(snapshot.resolution->transaction_hash->c_str()) : nullptr; |
| 1242 | const auto error = snapshot.error_message ? env->NewStringUTF(snapshot.error_message->c_str()) : nullptr; |
| 1243 | const auto retry_after = snapshot.resolution && snapshot.resolution->retry_after_hint_ms |
| 1244 | ? *snapshot.resolution->retry_after_hint_ms : 4000; |
| 1245 | if (env->ExceptionCheck()) return nullptr; |
| 1246 | return env->NewObject(cls, constructor, operation_id, static_cast<jint>(snapshot.phase), |
| 1247 | transaction_hash, error, static_cast<jlong>(retry_after)); |
| 1248 | } catch (const std::bad_alloc &) { |
| 1249 | throw_java(env, "java/lang/OutOfMemoryError", "Could not resolve wallet send"); |
| 1250 | } catch (const std::exception &error) { |
| 1251 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1252 | } catch (...) { |
| 1253 | throw_java(env, "java/lang/IllegalStateException", "Could not resolve wallet send"); |
| 1254 | } |
| 1255 | return nullptr; |
| 1256 | } |
| 1257 |
| 1258 | extern "C" JNIEXPORT void JNICALL |
| 1259 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeRotateKey( |
| 1260 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, |
| 1261 | jstring operation_id, jobject callbacks) { |
| 1262 | try { |
| 1263 | auto client = get_client(handle); |
| 1264 | auto id = java_string(env, operation_id); |
| 1265 | if (!phrase_bytes || !callbacks) |
| 1266 | throw std::invalid_argument("Recovery phrase and callbacks are required"); |
| 1267 | auto callback_class = env->GetObjectClass(callbacks); |
| 1268 | auto replacement_callback = env->GetMethodID(callback_class, "replacement", "([B[B)V"); |
| 1269 | env->DeleteLocalRef(callback_class); |
| 1270 | if (!replacement_callback) return; |
| 1271 |
| 1272 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1273 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 1274 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1275 | if (env->ExceptionCheck()) return; |
| 1276 | SendScope scope(env, client, phrase, callbacks, id, we::SecretAccessReason::kPrepareKeyRotation); |
| 1277 |
| 1278 | // Use provider time for the signature rather than the device clock. |
| 1279 | const auto snapshot = client.wallet->refresh().snapshot; |
| 1280 | if (snapshot.account_resource.phase != we::ResourcePhase::kReady || !snapshot.account) |
| 1281 | throw std::runtime_error(snapshot.account_resource.error |
| 1282 | ? snapshot.account_resource.error->developer_message : "Could not load wallet account"); |
| 1283 | constexpr uint64_t validity_seconds = 120; |
| 1284 | if (snapshot.account->sync_utime > std::numeric_limits<uint32_t>::max() - validity_seconds) |
| 1285 | throw std::runtime_error("Key rotation expiration exceeds the supported range"); |
| 1286 | auto prepared = client.wallet->prepare_key_rotation({ |
| 1287 | snapshot.account->sync_utime + validity_seconds, we::KeyRotationMessageKind::kExternal}); |
| 1288 | client.hosts->secret = nullptr; |
| 1289 |
| 1290 | { |
| 1291 | SensitiveString replacement(0); |
| 1292 | replacement.value.swap(prepared.replacement_recovery_phrase.phrase); |
| 1293 | if (prepared.new_public_key.size() != 32) |
| 1294 | throw std::runtime_error("Unexpected signing public key size"); |
| 1295 | auto public_key = env->NewByteArray(32); |
| 1296 | if (!public_key) return; |
| 1297 | env->SetByteArrayRegion(public_key, 0, 32, |
| 1298 | reinterpret_cast<const jbyte *>(prepared.new_public_key.data())); |
| 1299 | if (env->ExceptionCheck()) return; |
| 1300 | auto bytes = env->NewByteArray(static_cast<jsize>(replacement.value.size())); |
| 1301 | if (!bytes) return; |
| 1302 | env->SetByteArrayRegion(bytes, 0, static_cast<jsize>(replacement.value.size()), |
| 1303 | reinterpret_cast<const jbyte *>(replacement.value.data())); |
| 1304 | if (env->ExceptionCheck()) return; |
| 1305 | // This callback waits for Java to finish saving the phrase. Never submit first. |
| 1306 | env->CallVoidMethod(callbacks, replacement_callback, bytes, public_key); |
| 1307 | if (env->ExceptionCheck()) return; |
| 1308 | env->DeleteLocalRef(bytes); |
| 1309 | env->DeleteLocalRef(public_key); |
| 1310 | } |
| 1311 |
| 1312 | client.wallet->send_boc({id, false, prepared.signed_boc, prepared.seqno, prepared.valid_until}); |
| 1313 | } catch (const std::bad_alloc &) { |
| 1314 | throw_java(env, "java/lang/OutOfMemoryError", "Could not rotate wallet key"); |
| 1315 | } catch (const std::exception &error) { |
| 1316 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1317 | } catch (...) { |
| 1318 | throw_java(env, "java/lang/IllegalStateException", "Could not rotate wallet key"); |
| 1319 | } |
| 1320 | } |
| 1321 |
| 1322 | extern "C" JNIEXPORT void JNICALL |
| 1323 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeClose(JNIEnv *env, jclass, jlong handle) { |
| 1324 | try { |
| 1325 | std::shared_ptr<we::WalletClient> client; |
| 1326 | { |
| 1327 | std::lock_guard<std::mutex> lock(clients_mutex); |
| 1328 | auto it = clients.find(handle); |
| 1329 | if (it == clients.end()) return; |
| 1330 | client = std::move(it->second.wallet); |
| 1331 | clients.erase(it); |
| 1332 | } |
| 1333 | // Never hold the registry lock while entering Rust or running host callbacks. |
| 1334 | client->shutdown(); |
| 1335 | } catch (const std::exception &error) { |
| 1336 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1337 | } catch (...) { |
| 1338 | throw_java(env, "java/lang/IllegalStateException", "Could not close wallet engine"); |
| 1339 | } |
| 1340 | } |
| 1341 |
| 1342 |
| 1343 | extern "C" JNIEXPORT jobject JNICALL |
| 1344 | Java_org_telegram_ui_Wallet_WalletEngine2_nativeEmulateSendNFT( |
| 1345 | JNIEnv *env, jclass, jlong handle, jstring recipient, jstring nft_address, |
| 1346 | jbyteArray comment_bytes, jstring operation_id, jlong attached, jlong forward) { |
| 1347 | try { |
| 1348 | auto client = get_client(handle); |
| 1349 | const auto destination = java_string(env, recipient); |
| 1350 | const auto intent = nft_transfer_intent(env, comment_bytes, destination, java_string(env, nft_address), attached, forward); |
| 1351 | const auto preview = client.wallet->preview_nft_transfer({java_string(env, operation_id), intent}); |
| 1352 | // The transferred asset is an NFT, so don't present attached execution funds as a coin payment. |
| 1353 | return preview_transaction(env, preview, destination, 0); |
| 1354 | } catch (const std::bad_alloc &) { |
| 1355 | throw_java(env, "java/lang/OutOfMemoryError", "Could not preview NFT transfer"); |
| 1356 | } catch (const std::exception &error) { |
| 1357 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1358 | } catch (...) { |
| 1359 | throw_java(env, "java/lang/IllegalStateException", "Could not preview NFT transfer"); |
| 1360 | } |
| 1361 | return nullptr; |
| 1362 | } |
| 1363 |
| 1364 | extern "C" JNIEXPORT jobject JNICALL |
| 1365 | Java_org_telegram_ui_Wallet_WalletEngine2_nativePrepareSendNFT( |
| 1366 | JNIEnv *env, jclass, jlong handle, jbyteArray phrase_bytes, jstring recipient, |
| 1367 | jstring nft_address, jbyteArray comment_bytes, jstring operation_id, jlong attached, jlong forward) { |
| 1368 | try { |
| 1369 | auto client = get_client(handle); |
| 1370 | const auto intent = nft_transfer_intent(env, comment_bytes, java_string(env, recipient), java_string(env, nft_address), attached, forward); |
| 1371 | if (!phrase_bytes) throw std::invalid_argument("Recovery phrase is required"); |
| 1372 | SensitiveString phrase(static_cast<size_t>(env->GetArrayLength(phrase_bytes))); |
| 1373 | env->GetByteArrayRegion(phrase_bytes, 0, static_cast<jsize>(phrase.value.size()), |
| 1374 | reinterpret_cast<jbyte *>(phrase.value.data())); |
| 1375 | if (env->ExceptionCheck()) return nullptr; |
| 1376 | SecretScope scope(client, phrase, we::SecretAccessReason::kSignTransfer); |
| 1377 | const auto prepared = client.wallet->prepare_nft_transfer({java_string(env, operation_id), intent}); |
| 1378 | const auto external = env->NewStringUTF(prepared.external_boc.c_str()); |
| 1379 | if (!external) return nullptr; |
| 1380 | const auto cls = env->FindClass("org/telegram/ui/Wallet/WalletEngine2$PreparedSend"); |
| 1381 | if (!cls) return nullptr; |
| 1382 | const auto constructor = env->GetMethodID(cls, "<init>", |
| 1383 | "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V"); |
| 1384 | if (!constructor) return nullptr; |
| 1385 | // The current API requests normal delivery; no relayer/gasless route was selected. |
| 1386 | return env->NewObject(cls, constructor, external, nullptr, nullptr); |
| 1387 | } catch (const std::bad_alloc &) { |
| 1388 | throw_java(env, "java/lang/OutOfMemoryError", "Could not prepare NFT transfer"); |
| 1389 | } catch (const std::exception &error) { |
| 1390 | throw_java(env, "java/lang/IllegalStateException", error.what()); |
| 1391 | } catch (...) { |
| 1392 | throw_java(env, "java/lang/IllegalStateException", "Could not prepare NFT transfer"); |
| 1393 | } |
| 1394 | return nullptr; |
| 1395 | } |
| 1396 |