| 1 | // Copyright (c) 2017-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | // |
| 29 | |
| 30 | #include "device_trezor.hpp" |
| 31 | #include <boost/filesystem.hpp> |
| 32 | #include <boost/algorithm/string/predicate.hpp> |
| 33 | |
| 34 | namespace hw { |
| 35 | namespace trezor { |
| 36 | |
| 37 | #ifdef WITH_DEVICE_TREZOR |
| 38 | |
| 39 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 40 | #define MONERO_DEFAULT_LOG_CATEGORY "device.trezor" |
| 41 | |
| 42 | #define HW_TREZOR_NAME "Trezor" |
| 43 | |
| 44 | static device_trezor *trezor_device = nullptr; |
| 45 | static device_trezor *ensure_trezor_device(){ |
| 46 | if (!trezor_device) { |
| 47 | trezor_device = new device_trezor(); |
| 48 | trezor_device->set_name(HW_TREZOR_NAME); |
| 49 | } |
| 50 | return trezor_device; |
| 51 | } |
| 52 | |
| 53 | void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) { |
| 54 | registry.insert(std::make_pair(HW_TREZOR_NAME, std::unique_ptr<device>(ensure_trezor_device()))); |
| 55 | } |
| 56 | |
| 57 | void register_all() { |
| 58 | hw::register_device(HW_TREZOR_NAME, ensure_trezor_device()); |
| 59 | } |
| 60 | |
| 61 | device_trezor::device_trezor() { |
| 62 | m_live_refresh_in_progress = false; |
| 63 | m_live_refresh_enabled = true; |
| 64 | m_live_refresh_thread_running = false; |
| 65 | } |
| 66 | |
| 67 | device_trezor::~device_trezor() { |
| 68 | try { |
| 69 | device_trezor::disconnect(); |
| 70 | device_trezor::release(); |
| 71 | } catch(std::exception const& e){ |
| 72 | MWARNING("Could not disconnect and release: " << e.what()); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | bool device_trezor::init() |
| 77 | { |
| 78 | m_live_refresh_in_progress = false; |
| 79 | bool r = device_trezor_base::init(); |
| 80 | if (r && !m_live_refresh_thread) |
| 81 | { |
| 82 | m_live_refresh_thread_running = true; |
| 83 | m_live_refresh_thread.reset(new boost::thread(boost::bind(&device_trezor::live_refresh_thread_main, this))); |
| 84 | } |
| 85 | return r; |
| 86 | } |
| 87 | |
| 88 | bool device_trezor::release() |
| 89 | { |
| 90 | m_live_refresh_in_progress = false; |
| 91 | m_live_refresh_thread_running = false; |
| 92 | if (m_live_refresh_thread) |
| 93 | { |
| 94 | m_live_refresh_thread->join(); |
| 95 | m_live_refresh_thread = nullptr; |
| 96 | } |
| 97 | return device_trezor_base::release(); |
| 98 | } |
| 99 | |
| 100 | bool device_trezor::disconnect() |
| 101 | { |
| 102 | m_live_refresh_in_progress = false; |
| 103 | return device_trezor_base::disconnect(); |
| 104 | } |
| 105 | |
| 106 | void device_trezor::device_state_initialize_unsafe() |
| 107 | { |
| 108 | require_connected(); |
| 109 | if (m_live_refresh_in_progress) |
| 110 | { |
| 111 | try |
| 112 | { |
| 113 | live_refresh_finish_unsafe(); |
| 114 | } |
| 115 | catch(const std::exception & e) |
| 116 | { |
| 117 | MERROR("Live refresh could not be terminated: " << e.what()); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | m_live_refresh_in_progress = false; |
| 122 | device_trezor_base::device_state_initialize_unsafe(); |
| 123 | } |
| 124 | |
| 125 | void device_trezor::live_refresh_thread_main() |
| 126 | { |
| 127 | while(m_live_refresh_thread_running) |
| 128 | { |
| 129 | boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); |
| 130 | if (!m_live_refresh_in_progress) |
| 131 | { |
| 132 | continue; |
| 133 | } |
| 134 | |
| 135 | TREZOR_AUTO_LOCK_DEVICE(); |
| 136 | if (!m_transport || !m_live_refresh_in_progress) |
| 137 | { |
| 138 | continue; |
| 139 | } |
| 140 | |
| 141 | auto current_time = std::chrono::steady_clock::now(); |
| 142 | if (current_time - m_last_live_refresh_time <= std::chrono::minutes(5)) |
| 143 | { |
| 144 | continue; |
| 145 | } |
| 146 | |
| 147 | MTRACE("Closing live refresh process due to inactivity"); |
| 148 | try |
| 149 | { |
| 150 | live_refresh_finish(); |
| 151 | } |
| 152 | catch(const std::exception &e) |
| 153 | { |
| 154 | MWARNING("Live refresh auto-finish failed: " << e.what()); |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | /* ======================================================================= */ |
| 160 | /* WALLET & ADDRESS */ |
| 161 | /* ======================================================================= */ |
| 162 | |
| 163 | bool device_trezor::get_public_address(cryptonote::account_public_address &pubkey) { |
| 164 | try { |
| 165 | auto res = get_address(); |
| 166 | |
| 167 | cryptonote::address_parse_info info{}; |
| 168 | bool r = cryptonote::get_account_address_from_str(info, this->network_type, res->address()); |
| 169 | CHECK_AND_ASSERT_MES(r, false, "Could not parse returned address. Address parse failed: " + res->address()); |
| 170 | CHECK_AND_ASSERT_MES(!info.is_subaddress, false, "Trezor returned a sub address"); |
| 171 | |
| 172 | pubkey = info.address; |
| 173 | return true; |
| 174 | |
| 175 | } catch(std::exception const& e){ |
| 176 | MERROR("Get public address exception: " << e.what()); |
| 177 | return false; |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | bool device_trezor::get_public_address_with_no_passphrase(cryptonote::account_public_address &pubkey) { |
| 182 | m_reply_with_empty_passphrase = true; |
| 183 | const auto empty_passphrase_reverter = epee::misc_utils::create_scope_leave_handler([&]() { |
| 184 | m_reply_with_empty_passphrase = false; |
| 185 | }); |
| 186 | |
| 187 | return get_public_address(pubkey); |
| 188 | } |
| 189 | |
| 190 | bool device_trezor::get_secret_keys(crypto::secret_key &viewkey , crypto::secret_key &spendkey) { |
| 191 | try { |
| 192 | MDEBUG("Loading view-only key from the Trezor. Please check the Trezor for a confirmation."); |
| 193 | auto res = get_view_key(); |
| 194 | CHECK_AND_ASSERT_MES(res->watch_key().size() == 32, false, "Trezor returned invalid view key"); |
| 195 | |
| 196 | // Trezor does not make use of spendkey of the device API. |
| 197 | // Ledger loads encrypted spendkey, Trezor loads null key (never leaves device). |
| 198 | // In the test (debugging mode) we need to leave this field intact as it is already set by |
| 199 | // the debugging code and need to remain same for the testing purposes. |
| 200 | #ifndef WITH_TREZOR_DEBUGGING |
| 201 | spendkey = crypto::null_skey; // not given |
| 202 | #endif |
| 203 | |
| 204 | memcpy(viewkey.data, res->watch_key().data(), 32); |
| 205 | |
| 206 | return true; |
| 207 | |
| 208 | } catch(std::exception const& e){ |
| 209 | MERROR("Get secret keys exception: " << e.what()); |
| 210 | return false; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | void device_trezor::display_address(const cryptonote::subaddress_index& index, const boost::optional<crypto::hash8> &payment_id) { |
| 215 | get_address(index, payment_id, true); |
| 216 | } |
| 217 | |
| 218 | void device_trezor::reset_session() { |
| 219 | m_device_session_id.clear(); |
| 220 | } |
| 221 | |
| 222 | bool device_trezor::seen_passphrase_entry_prompt() { |
| 223 | return m_seen_passphrase_entry_message; |
| 224 | } |
| 225 | |
| 226 | void device_trezor::set_use_empty_passphrase(bool always_use_empty_passphrase) { |
| 227 | m_always_use_empty_passphrase = always_use_empty_passphrase; |
| 228 | } |
| 229 | |
| 230 | /* ======================================================================= */ |
| 231 | /* Helpers */ |
| 232 | /* ======================================================================= */ |
| 233 | |
| 234 | /* ======================================================================= */ |
| 235 | /* TREZOR PROTOCOL */ |
| 236 | /* ======================================================================= */ |
| 237 | |
| 238 | std::shared_ptr<messages::monero::MoneroAddress> device_trezor::get_address( |
| 239 | const boost::optional<cryptonote::subaddress_index> & subaddress, |
| 240 | const boost::optional<crypto::hash8> & payment_id, |
| 241 | bool show_address, |
| 242 | const boost::optional<std::vector<uint32_t>> & path, |
| 243 | const boost::optional<cryptonote::network_type> & network_type){ |
| 244 | CHECK_AND_ASSERT_THROW_MES(!payment_id || !subaddress || subaddress->is_zero(), "Subaddress cannot be integrated"); |
| 245 | TREZOR_AUTO_LOCK_CMD(); |
| 246 | require_connected(); |
| 247 | device_state_initialize_unsafe(); |
| 248 | require_initialized(); |
| 249 | |
| 250 | auto req = std::make_shared<messages::monero::MoneroGetAddress>(); |
| 251 | this->set_msg_addr<messages::monero::MoneroGetAddress>(req.get(), path, network_type); |
| 252 | req->set_show_display(show_address); |
| 253 | if (subaddress){ |
| 254 | req->set_account(subaddress->major); |
| 255 | req->set_minor(subaddress->minor); |
| 256 | } |
| 257 | if (payment_id){ |
| 258 | req->set_payment_id(std::string(payment_id->data, 8)); |
| 259 | } |
| 260 | |
| 261 | auto response = this->client_exchange<messages::monero::MoneroAddress>(req); |
| 262 | MTRACE("Get address response received"); |
| 263 | return response; |
| 264 | } |
| 265 | |
| 266 | std::shared_ptr<messages::monero::MoneroWatchKey> device_trezor::get_view_key( |
| 267 | const boost::optional<std::vector<uint32_t>> & path, |
| 268 | const boost::optional<cryptonote::network_type> & network_type){ |
| 269 | TREZOR_AUTO_LOCK_CMD(); |
| 270 | require_connected(); |
| 271 | device_state_initialize_unsafe(); |
| 272 | require_initialized(); |
| 273 | |
| 274 | auto req = std::make_shared<messages::monero::MoneroGetWatchKey>(); |
| 275 | this->set_msg_addr<messages::monero::MoneroGetWatchKey>(req.get(), path, network_type); |
| 276 | |
| 277 | auto response = this->client_exchange<messages::monero::MoneroWatchKey>(req); |
| 278 | MTRACE("Get watch key response received"); |
| 279 | return response; |
| 280 | } |
| 281 | |
| 282 | bool device_trezor::is_get_tx_key_supported() const |
| 283 | { |
| 284 | require_initialized(); |
| 285 | return get_version() > pack_version(2, 0, 10); |
| 286 | } |
| 287 | |
| 288 | void device_trezor::load_tx_key_data(::hw::device_cold::tx_key_data_t & res, const std::string & tx_aux_data) |
| 289 | { |
| 290 | protocol::tx::load_tx_key_data(res, tx_aux_data); |
| 291 | } |
| 292 | |
| 293 | void device_trezor::get_tx_key( |
| 294 | std::vector<::crypto::secret_key> & tx_keys, |
| 295 | const ::hw::device_cold::tx_key_data_t & tx_aux_data, |
| 296 | const ::crypto::secret_key & view_key_priv) |
| 297 | { |
| 298 | TREZOR_AUTO_LOCK_CMD(); |
| 299 | require_connected(); |
| 300 | device_state_initialize_unsafe(); |
| 301 | require_initialized(); |
| 302 | |
| 303 | auto req = protocol::tx::get_tx_key(tx_aux_data); |
| 304 | this->set_msg_addr<messages::monero::MoneroGetTxKeyRequest>(req.get()); |
| 305 | |
| 306 | auto response = this->client_exchange<messages::monero::MoneroGetTxKeyAck>(req); |
| 307 | MTRACE("Get TX key response received"); |
| 308 | |
| 309 | protocol::tx::get_tx_key_ack(tx_keys, tx_aux_data.tx_prefix_hash, view_key_priv, response); |
| 310 | } |
| 311 | |
| 312 | void device_trezor::ki_sync(wallet_shim * wallet, |
| 313 | const std::vector<tools::wallet2::transfer_details> & transfers, |
| 314 | hw::device_cold::exported_key_image & ski) |
| 315 | { |
| 316 | #define EVENT_PROGRESS(P) do { if (m_callback) {(m_callback)->on_progress(device_cold::op_progress(P)); } }while(0) |
| 317 | |
| 318 | TREZOR_AUTO_LOCK_CMD(); |
| 319 | require_connected(); |
| 320 | device_state_initialize_unsafe(); |
| 321 | require_initialized(); |
| 322 | |
| 323 | std::shared_ptr<messages::monero::MoneroKeyImageExportInitRequest> req; |
| 324 | |
| 325 | std::vector<protocol::ki::MoneroTransferDetails> mtds; |
| 326 | std::vector<protocol::ki::MoneroExportedKeyImage> kis; |
| 327 | protocol::ki::key_image_data(wallet, transfers, mtds); |
| 328 | protocol::ki::generate_commitment(mtds, transfers, req); |
| 329 | |
| 330 | EVENT_PROGRESS(0.); |
| 331 | this->set_msg_addr<messages::monero::MoneroKeyImageExportInitRequest>(req.get()); |
| 332 | auto ack1 = this->client_exchange<messages::monero::MoneroKeyImageExportInitAck>(req); |
| 333 | |
| 334 | const auto batch_size = 10; |
| 335 | const auto num_batches = (mtds.size() + batch_size - 1) / batch_size; |
| 336 | for(uint64_t cur = 0; cur < num_batches; ++cur){ |
| 337 | auto step_req = std::make_shared<messages::monero::MoneroKeyImageSyncStepRequest>(); |
| 338 | auto idx_finish = std::min(static_cast<uint64_t>((cur + 1) * batch_size), static_cast<uint64_t>(mtds.size())); |
| 339 | for(uint64_t idx = cur * batch_size; idx < idx_finish; ++idx){ |
| 340 | auto added_tdis = step_req->add_tdis(); |
| 341 | CHECK_AND_ASSERT_THROW_MES(idx < mtds.size(), "Invalid transfer detail index"); |
| 342 | *added_tdis = mtds[idx]; |
| 343 | } |
| 344 | |
| 345 | auto step_ack = this->client_exchange<messages::monero::MoneroKeyImageSyncStepAck>(step_req); |
| 346 | auto kis_size = step_ack->kis_size(); |
| 347 | kis.reserve(static_cast<size_t>(kis_size)); |
| 348 | for(int i = 0; i < kis_size; ++i){ |
| 349 | auto ckis = step_ack->kis(i); |
| 350 | kis.push_back(ckis); |
| 351 | } |
| 352 | |
| 353 | MTRACE("Batch " << cur << " / " << num_batches << " batches processed"); |
| 354 | EVENT_PROGRESS((double)cur * batch_size / mtds.size()); |
| 355 | } |
| 356 | EVENT_PROGRESS(1.); |
| 357 | |
| 358 | auto final_req = std::make_shared<messages::monero::MoneroKeyImageSyncFinalRequest>(); |
| 359 | auto final_ack = this->client_exchange<messages::monero::MoneroKeyImageSyncFinalAck>(final_req); |
| 360 | ski.reserve(kis.size()); |
| 361 | |
| 362 | for(auto & sub : kis){ |
| 363 | ::crypto::signature sig{}; |
| 364 | ::crypto::key_image ki; |
| 365 | char buff[sizeof(ki.data)*3]; |
| 366 | |
| 367 | size_t buff_len = sizeof(buff); |
| 368 | |
| 369 | protocol::crypto::chacha::decrypt(sub.blob().data(), sub.blob().size(), |
| 370 | reinterpret_cast<const uint8_t *>(final_ack->enc_key().data()), |
| 371 | reinterpret_cast<const uint8_t *>(sub.iv().data()), buff, &buff_len); |
| 372 | CHECK_AND_ASSERT_THROW_MES(buff_len == sizeof(buff), "Plaintext size invalid"); |
| 373 | |
| 374 | memcpy(ki.data, buff, sizeof(ki.data)); |
| 375 | memcpy(sig.c.data, buff + sizeof(ki.data), sizeof(ki.data)); |
| 376 | memcpy(sig.r.data, buff + 2*sizeof(ki.data), sizeof(ki.data)); |
| 377 | ski.push_back(std::make_pair(ki, sig)); |
| 378 | } |
| 379 | #undef EVENT_PROGRESS |
| 380 | } |
| 381 | |
| 382 | bool device_trezor::is_live_refresh_supported() const |
| 383 | { |
| 384 | require_initialized(); |
| 385 | return get_version() > pack_version(2, 0, 10); |
| 386 | } |
| 387 | |
| 388 | bool device_trezor::is_live_refresh_enabled() const |
| 389 | { |
| 390 | return is_live_refresh_supported() && (mode == NONE || mode == TRANSACTION_PARSE) && m_live_refresh_enabled; |
| 391 | } |
| 392 | |
| 393 | bool device_trezor::has_ki_live_refresh() const |
| 394 | { |
| 395 | try{ |
| 396 | return is_live_refresh_enabled(); |
| 397 | } catch(const std::exception & e){ |
| 398 | MERROR("Could not detect if live refresh is enabled: " << e.what()); |
| 399 | } |
| 400 | return false; |
| 401 | } |
| 402 | |
| 403 | void device_trezor::live_refresh_start() |
| 404 | { |
| 405 | TREZOR_AUTO_LOCK_CMD(); |
| 406 | require_connected(); |
| 407 | live_refresh_start_unsafe(); |
| 408 | } |
| 409 | |
| 410 | void device_trezor::live_refresh_start_unsafe() |
| 411 | { |
| 412 | device_state_initialize_unsafe(); |
| 413 | require_initialized(); |
| 414 | |
| 415 | auto req = std::make_shared<messages::monero::MoneroLiveRefreshStartRequest>(); |
| 416 | this->set_msg_addr<messages::monero::MoneroLiveRefreshStartRequest>(req.get()); |
| 417 | this->client_exchange<messages::monero::MoneroLiveRefreshStartAck>(req); |
| 418 | m_live_refresh_in_progress = true; |
| 419 | m_last_live_refresh_time = std::chrono::steady_clock::now(); |
| 420 | } |
| 421 | |
| 422 | void device_trezor::live_refresh( |
| 423 | const ::crypto::secret_key & view_key_priv, |
| 424 | const crypto::public_key& out_key, |
| 425 | const crypto::key_derivation& recv_derivation, |
| 426 | size_t real_output_index, |
| 427 | const cryptonote::subaddress_index& received_index, |
| 428 | cryptonote::keypair& in_ephemeral, |
| 429 | crypto::key_image& ki |
| 430 | ) |
| 431 | { |
| 432 | TREZOR_AUTO_LOCK_CMD(); |
| 433 | require_connected(); |
| 434 | |
| 435 | if (!m_live_refresh_in_progress) |
| 436 | { |
| 437 | live_refresh_start_unsafe(); |
| 438 | } |
| 439 | |
| 440 | m_last_live_refresh_time = std::chrono::steady_clock::now(); |
| 441 | |
| 442 | auto req = std::make_shared<messages::monero::MoneroLiveRefreshStepRequest>(); |
| 443 | req->set_out_key(out_key.data, 32); |
| 444 | req->set_recv_deriv(recv_derivation.data, 32); |
| 445 | req->set_real_out_idx(real_output_index); |
| 446 | req->set_sub_addr_major(received_index.major); |
| 447 | req->set_sub_addr_minor(received_index.minor); |
| 448 | |
| 449 | auto ack = this->client_exchange<messages::monero::MoneroLiveRefreshStepAck>(req); |
| 450 | protocol::ki::live_refresh_ack(view_key_priv, out_key, ack, in_ephemeral, ki); |
| 451 | } |
| 452 | |
| 453 | void device_trezor::live_refresh_finish_unsafe() |
| 454 | { |
| 455 | auto req = std::make_shared<messages::monero::MoneroLiveRefreshFinalRequest>(); |
| 456 | this->client_exchange<messages::monero::MoneroLiveRefreshFinalAck>(req); |
| 457 | m_live_refresh_in_progress = false; |
| 458 | } |
| 459 | |
| 460 | void device_trezor::live_refresh_finish() |
| 461 | { |
| 462 | TREZOR_AUTO_LOCK_CMD(); |
| 463 | require_connected(); |
| 464 | if (m_live_refresh_in_progress) |
| 465 | { |
| 466 | live_refresh_finish_unsafe(); |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | void device_trezor::computing_key_images(bool started) |
| 471 | { |
| 472 | try |
| 473 | { |
| 474 | if (!is_live_refresh_enabled()) |
| 475 | { |
| 476 | return; |
| 477 | } |
| 478 | |
| 479 | // React only on termination as the process can auto-start itself. |
| 480 | if (!started && m_live_refresh_in_progress) |
| 481 | { |
| 482 | live_refresh_finish(); |
| 483 | } |
| 484 | } |
| 485 | catch(const std::exception & e) |
| 486 | { |
| 487 | MWARNING("KI computation state change failed, started: " << started << ", e: " << e.what()); |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | bool device_trezor::compute_key_image( |
| 492 | const ::cryptonote::account_keys& ack, |
| 493 | const ::crypto::public_key& out_key, |
| 494 | const ::crypto::key_derivation& recv_derivation, |
| 495 | size_t real_output_index, |
| 496 | const ::cryptonote::subaddress_index& received_index, |
| 497 | ::cryptonote::keypair& in_ephemeral, |
| 498 | ::crypto::key_image& ki) |
| 499 | { |
| 500 | if (!is_live_refresh_enabled()) |
| 501 | { |
| 502 | return false; |
| 503 | } |
| 504 | |
| 505 | live_refresh(ack.m_view_secret_key, out_key, recv_derivation, real_output_index, received_index, in_ephemeral, ki); |
| 506 | return true; |
| 507 | } |
| 508 | |
| 509 | void device_trezor::tx_sign(wallet_shim * wallet, |
| 510 | const tools::wallet2::unsigned_tx_set & unsigned_tx, |
| 511 | tools::wallet2::signed_tx_set & signed_tx, |
| 512 | hw::tx_aux_data & aux_data) |
| 513 | { |
| 514 | CHECK_AND_ASSERT_THROW_MES(std::get<0>(unsigned_tx.transfers) == 0, "Unsuported non zero offset"); |
| 515 | |
| 516 | TREZOR_AUTO_LOCK_CMD(); |
| 517 | require_connected(); |
| 518 | device_state_initialize_unsafe(); |
| 519 | require_initialized(); |
| 520 | transaction_versions_check(unsigned_tx, aux_data); |
| 521 | |
| 522 | const size_t num_tx = unsigned_tx.txes.size(); |
| 523 | m_num_transations_to_sign = num_tx; |
| 524 | signed_tx.key_images.clear(); |
| 525 | signed_tx.key_images.resize(std::get<2>(unsigned_tx.transfers).size()); |
| 526 | |
| 527 | for(size_t tx_idx = 0; tx_idx < num_tx; ++tx_idx) { |
| 528 | std::shared_ptr<protocol::tx::Signer> signer; |
| 529 | tx_sign(wallet, unsigned_tx, tx_idx, aux_data, signer); |
| 530 | |
| 531 | auto & cdata = signer->tdata(); |
| 532 | auto aux_info_cur = signer->store_tx_aux_info(); |
| 533 | aux_data.tx_device_aux.emplace_back(aux_info_cur); |
| 534 | |
| 535 | // Pending tx reconstruction |
| 536 | signed_tx.ptx.emplace_back(); |
| 537 | auto & cpend = signed_tx.ptx.back(); |
| 538 | cpend.tx = cdata.tx; |
| 539 | cpend.dust = 0; |
| 540 | cpend.fee = cpend.tx.rct_signatures.txnFee; |
| 541 | cpend.dust_added_to_fee = false; |
| 542 | cpend.change_dts = cdata.tx_data.change_dts; |
| 543 | cpend.selected_transfers = cdata.tx_data.selected_transfers; |
| 544 | cpend.key_images = ""; |
| 545 | cpend.dests = cdata.tx_data.dests; |
| 546 | cpend.construction_data = cdata.tx_data; |
| 547 | |
| 548 | // Transaction check |
| 549 | try { |
| 550 | MDEBUG("signed transaction: " << cryptonote::get_transaction_hash(cpend.tx) << ENDL << cryptonote::obj_to_json_str(cpend.tx) << ENDL); |
| 551 | transaction_check(cdata, aux_data); |
| 552 | } catch(const std::exception &e){ |
| 553 | throw exc::ProtocolException(std::string("Transaction verification failed: ") + e.what()); |
| 554 | } |
| 555 | |
| 556 | std::string key_images; |
| 557 | bool all_are_txin_to_key = std::all_of(cdata.tx.vin.begin(), cdata.tx.vin.end(), [&](const cryptonote::txin_v& s_e) -> bool |
| 558 | { |
| 559 | CHECKED_GET_SPECIFIC_VARIANT(s_e, const cryptonote::txin_to_key, in, false); |
| 560 | key_images += boost::to_string(in.k_image) + " "; |
| 561 | return true; |
| 562 | }); |
| 563 | if(!all_are_txin_to_key) { |
| 564 | throw std::invalid_argument("Not all are txin_to_key"); |
| 565 | } |
| 566 | cpend.key_images = key_images; |
| 567 | |
| 568 | // KI sync |
| 569 | for(size_t cidx=0, trans_max=std::get<2>(unsigned_tx.transfers).size(); cidx < trans_max; ++cidx){ |
| 570 | signed_tx.key_images[cidx] = std::get<2>(unsigned_tx.transfers)[cidx].m_key_image; |
| 571 | } |
| 572 | |
| 573 | size_t num_sources = cdata.tx_data.sources.size(); |
| 574 | CHECK_AND_ASSERT_THROW_MES(num_sources == cdata.source_permutation.size(), "Invalid permutation size"); |
| 575 | CHECK_AND_ASSERT_THROW_MES(num_sources == cdata.tx.vin.size(), "Invalid tx.vin size"); |
| 576 | for(size_t src_idx = 0; src_idx < num_sources; ++src_idx){ |
| 577 | size_t idx_mapped = cdata.source_permutation[src_idx]; |
| 578 | CHECK_AND_ASSERT_THROW_MES(idx_mapped < cdata.tx_data.selected_transfers.size(), "Invalid idx_mapped"); |
| 579 | CHECK_AND_ASSERT_THROW_MES(src_idx < cdata.tx.vin.size(), "Invalid idx_mapped"); |
| 580 | |
| 581 | size_t idx_map_src = cdata.tx_data.selected_transfers[idx_mapped]; |
| 582 | CHECK_AND_ASSERT_THROW_MES(idx_map_src >= std::get<0>(unsigned_tx.transfers), "Invalid offset"); |
| 583 | |
| 584 | idx_map_src -= std::get<0>(unsigned_tx.transfers); |
| 585 | CHECK_AND_ASSERT_THROW_MES(idx_map_src < signed_tx.key_images.size(), "Invalid key image index"); |
| 586 | |
| 587 | const auto vini = boost::get<cryptonote::txin_to_key>(cdata.tx.vin[src_idx]); |
| 588 | signed_tx.key_images[idx_map_src] = vini.k_image; |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | if (m_callback){ |
| 593 | m_callback->on_progress(device_cold::tx_progress(m_num_transations_to_sign, m_num_transations_to_sign, 1, 1, 1, 1)); |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | void device_trezor::tx_sign(wallet_shim * wallet, |
| 598 | const tools::wallet2::unsigned_tx_set & unsigned_tx, |
| 599 | size_t idx, |
| 600 | hw::tx_aux_data & aux_data, |
| 601 | std::shared_ptr<protocol::tx::Signer> & signer) |
| 602 | { |
| 603 | #define EVENT_PROGRESS(S, SUB, SUBMAX) do { if (m_callback) { \ |
| 604 | (m_callback)->on_progress(device_cold::tx_progress(idx, m_num_transations_to_sign, S, 10, SUB, SUBMAX)); \ |
| 605 | } }while(0) |
| 606 | |
| 607 | require_connected(); |
| 608 | if (idx > 0) |
| 609 | device_state_initialize_unsafe(); |
| 610 | |
| 611 | require_initialized(); |
| 612 | EVENT_PROGRESS(0, 1, 1); |
| 613 | |
| 614 | CHECK_AND_ASSERT_THROW_MES(idx < unsigned_tx.txes.size(), "Invalid transaction index"); |
| 615 | signer = std::make_shared<protocol::tx::Signer>(wallet, &unsigned_tx, idx, &aux_data); |
| 616 | const tools::wallet2::tx_construction_data & cur_tx = unsigned_tx.txes[idx]; |
| 617 | unsigned long num_sources = cur_tx.sources.size(); |
| 618 | unsigned long num_outputs = cur_tx.splitted_dsts.size(); |
| 619 | |
| 620 | // Step: Init |
| 621 | auto init_msg = signer->step_init(); |
| 622 | this->set_msg_addr(init_msg.get()); |
| 623 | transaction_pre_check(init_msg); |
| 624 | EVENT_PROGRESS(1, 1, 1); |
| 625 | |
| 626 | auto response = this->client_exchange<messages::monero::MoneroTransactionInitAck>(init_msg); |
| 627 | signer->step_init_ack(response); |
| 628 | |
| 629 | // Step: Set transaction inputs |
| 630 | for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){ |
| 631 | auto src = signer->step_set_input(cur_src); |
| 632 | auto ack = this->client_exchange<messages::monero::MoneroTransactionSetInputAck>(src); |
| 633 | signer->step_set_input_ack(ack); |
| 634 | EVENT_PROGRESS(2, cur_src, num_sources); |
| 635 | } |
| 636 | |
| 637 | // Step: sort |
| 638 | signer->sort_ki(); |
| 639 | EVENT_PROGRESS(3, 1, 1); |
| 640 | |
| 641 | // Step: input_vini |
| 642 | for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){ |
| 643 | auto src = signer->step_set_vini_input(cur_src); |
| 644 | auto ack = this->client_exchange<messages::monero::MoneroTransactionInputViniAck>(src); |
| 645 | signer->step_set_vini_input_ack(ack); |
| 646 | EVENT_PROGRESS(4, cur_src, num_sources); |
| 647 | } |
| 648 | |
| 649 | // Step: all inputs set |
| 650 | auto all_inputs_set = signer->step_all_inputs_set(); |
| 651 | auto ack_all_inputs = this->client_exchange<messages::monero::MoneroTransactionAllInputsSetAck>(all_inputs_set); |
| 652 | signer->step_all_inputs_set_ack(ack_all_inputs); |
| 653 | EVENT_PROGRESS(5, 1, 1); |
| 654 | |
| 655 | // Step: outputs |
| 656 | for(size_t cur_dst = 0; cur_dst < num_outputs; ++cur_dst){ |
| 657 | auto src = signer->step_set_output(cur_dst); |
| 658 | auto ack = this->client_exchange<messages::monero::MoneroTransactionSetOutputAck>(src); |
| 659 | signer->step_set_output_ack(ack); |
| 660 | |
| 661 | // If BP is offloaded to host, another step with computed BP may be needed. |
| 662 | auto offloaded_bp = signer->step_rsig(cur_dst); |
| 663 | if (offloaded_bp){ |
| 664 | auto bp_ack = this->client_exchange<messages::monero::MoneroTransactionSetOutputAck>(offloaded_bp); |
| 665 | signer->step_set_rsig_ack(ack); |
| 666 | } |
| 667 | |
| 668 | EVENT_PROGRESS(6, cur_dst, num_outputs); |
| 669 | } |
| 670 | |
| 671 | // Step: all outs set |
| 672 | auto all_out_set = signer->step_all_outs_set(); |
| 673 | auto ack_all_out_set = this->client_exchange<messages::monero::MoneroTransactionAllOutSetAck>(all_out_set); |
| 674 | signer->step_all_outs_set_ack(ack_all_out_set, *this); |
| 675 | EVENT_PROGRESS(7, 1, 1); |
| 676 | |
| 677 | // Step: sign each input |
| 678 | for(size_t cur_src = 0; cur_src < num_sources; ++cur_src){ |
| 679 | auto src = signer->step_sign_input(cur_src); |
| 680 | auto ack_sign = this->client_exchange<messages::monero::MoneroTransactionSignInputAck>(src); |
| 681 | signer->step_sign_input_ack(ack_sign); |
| 682 | EVENT_PROGRESS(8, cur_src, num_sources); |
| 683 | } |
| 684 | |
| 685 | // Step: final |
| 686 | auto final_msg = signer->step_final(); |
| 687 | auto ack_final = this->client_exchange<messages::monero::MoneroTransactionFinalAck>(final_msg); |
| 688 | signer->step_final_ack(ack_final); |
| 689 | EVENT_PROGRESS(9, 1, 1); |
| 690 | #undef EVENT_PROGRESS |
| 691 | } |
| 692 | |
| 693 | unsigned device_trezor::client_version() |
| 694 | { |
| 695 | auto trezor_version = get_version(); |
| 696 | if (trezor_version < pack_version(2, 4, 3)){ |
| 697 | throw exc::TrezorException("Minimal Trezor firmware version is 2.4.3. Please update."); |
| 698 | } |
| 699 | |
| 700 | unsigned client_version = 3; |
| 701 | if (trezor_version >= pack_version(2, 5, 2)){ |
| 702 | client_version = 4; |
| 703 | } |
| 704 | |
| 705 | #ifdef WITH_TREZOR_DEBUGGING |
| 706 | // Override client version for tests |
| 707 | const char *env_trezor_client_version = nullptr; |
| 708 | if ((env_trezor_client_version = getenv("TREZOR_CLIENT_VERSION")) != nullptr){ |
| 709 | auto succ = epee::string_tools::get_xtype_from_string(client_version, env_trezor_client_version); |
| 710 | if (succ){ |
| 711 | MINFO("Trezor client version overriden by TREZOR_CLIENT_VERSION to: " << client_version); |
| 712 | } |
| 713 | } |
| 714 | #endif |
| 715 | return client_version; |
| 716 | } |
| 717 | |
| 718 | void device_trezor::transaction_versions_check(const ::tools::wallet2::unsigned_tx_set & unsigned_tx, hw::tx_aux_data & aux_data) |
| 719 | { |
| 720 | unsigned cversion = client_version(); |
| 721 | |
| 722 | if (aux_data.client_version){ |
| 723 | auto wanted_client_version = aux_data.client_version.get(); |
| 724 | if (wanted_client_version > cversion){ |
| 725 | throw exc::TrezorException("Trezor has too old firmware version. Please update."); |
| 726 | } else { |
| 727 | cversion = wanted_client_version; |
| 728 | } |
| 729 | } |
| 730 | aux_data.client_version = cversion; |
| 731 | } |
| 732 | |
| 733 | void device_trezor::transaction_pre_check(std::shared_ptr<messages::monero::MoneroTransactionInitRequest> init_msg) |
| 734 | { |
| 735 | CHECK_AND_ASSERT_THROW_MES(init_msg, "TransactionInitRequest is empty"); |
| 736 | CHECK_AND_ASSERT_THROW_MES(init_msg->has_tsx_data(), "TransactionInitRequest has no transaction data"); |
| 737 | CHECK_AND_ASSERT_THROW_MES(m_features, "Device state not initialized"); // make sure the caller did not reset features |
| 738 | } |
| 739 | |
| 740 | void device_trezor::transaction_check(const protocol::tx::TData & tdata, const hw::tx_aux_data & aux_data) |
| 741 | { |
| 742 | // Simple serialization check |
| 743 | cryptonote::blobdata tx_blob; |
| 744 | cryptonote::transaction tx_deserialized; |
| 745 | bool r = cryptonote::t_serializable_object_to_blob(tdata.tx, tx_blob); |
| 746 | CHECK_AND_ASSERT_THROW_MES(r, "Transaction serialization failed"); |
| 747 | r = cryptonote::parse_and_validate_tx_from_blob(tx_blob, tx_deserialized); |
| 748 | CHECK_AND_ASSERT_THROW_MES(r, "Transaction deserialization failed"); |
| 749 | |
| 750 | // Extras check |
| 751 | std::vector<cryptonote::tx_extra_field> tx_extra_fields; |
| 752 | cryptonote::tx_extra_nonce nonce; |
| 753 | |
| 754 | r = cryptonote::parse_tx_extra(tdata.tx.extra, tx_extra_fields); |
| 755 | CHECK_AND_ASSERT_THROW_MES(r, "tx.extra parsing failed"); |
| 756 | |
| 757 | const bool nonce_required = tdata.tsx_data.has_payment_id() && tdata.tsx_data.payment_id().size() > 0; |
| 758 | const bool has_nonce = cryptonote::find_tx_extra_field_by_type(tx_extra_fields, nonce); |
| 759 | CHECK_AND_ASSERT_THROW_MES(has_nonce || !nonce_required, "Transaction nonce not present"); |
| 760 | |
| 761 | if (nonce_required){ |
| 762 | const std::string & payment_id = tdata.tsx_data.payment_id(); |
| 763 | if (payment_id.size() == 32){ |
| 764 | crypto::hash payment_id_long{}; |
| 765 | CHECK_AND_ASSERT_THROW_MES(cryptonote::get_payment_id_from_tx_extra_nonce(nonce.nonce, payment_id_long), "Long payment ID not present"); |
| 766 | |
| 767 | } else if (payment_id.size() == 8){ |
| 768 | crypto::hash8 payment_id_short{}; |
| 769 | CHECK_AND_ASSERT_THROW_MES(cryptonote::get_encrypted_payment_id_from_tx_extra_nonce(nonce.nonce, payment_id_short), "Short payment ID not present"); |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | #else //WITH_DEVICE_TREZOR |
| 775 | |
| 776 | void register_all(std::map<std::string, std::unique_ptr<device>> ®istry) { |
| 777 | } |
| 778 | |
| 779 | void register_all() { |
| 780 | } |
| 781 | |
| 782 | #endif //WITH_DEVICE_TREZOR |
| 783 | }} |