wechat-protocol 2.4.1

Native WeChat transport, authentication and protocol codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Account data owned by NativeClient. Network workers take temporary snapshots;
//! they never hold the state lock while waiting for transport.
use super::{AccountState, NativeClient, NativeOptions};
use crate::errors::AccountInterrupted;
use anyhow::{ensure, Context, Result};
use serde::{Deserialize, Serialize};
use std::{
    future::Future,
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Condvar, Mutex, MutexGuard,
    },
    time::Duration,
};
use tokio::sync::Notify;
use zeroize::Zeroizing;

#[path = "account_components.rs"]
mod components;

/// The operation stopped before business bytes were handed to transport. This
/// marker is never attached to a timeout, rejected reply or post-handoff fence.
#[derive(Debug)]
pub struct NativeRequestNotSubmitted;

impl std::fmt::Display for NativeRequestNotSubmitted {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Native request stopped before business submission")
    }
}

impl std::error::Error for NativeRequestNotSubmitted {}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountLifecycle {
    Active,
    Stopped,
    Transferred,
}

/// Non-secret account lifecycle information. Credentials require an explicit
/// export; status/debug output must never contain an AccountState.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountStatus {
    pub lifecycle: AccountLifecycle,
    pub revision: u64,
    pub credential_generation: u64,
    pub in_flight: usize,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountIdentity {
    pub uin: u32,
    pub own_username: String,
}

/// Cheap authority check for account workers. It carries no credentials and
/// becomes invalid on shutdown or any accepted credential renewal. It cannot
/// replace the final submission guard on an authenticated signaling request.
#[derive(Clone)]
pub struct AccountLease {
    authority: Arc<Authority>,
    credential_generation: u64,
}
struct Authority {
    active: AtomicBool,
    credential_generation: AtomicU64,
}
impl AccountLease {
    pub fn current(&self) -> bool {
        self.authority.active.load(Ordering::Acquire)
            && self.authority.credential_generation.load(Ordering::Acquire)
                == self.credential_generation
    }
}

/// Correlation values must be recorded with the application's send intent before
/// submission. Neither a task ID nor a transport error authorizes a blind retry.
#[derive(Clone, Debug)]
pub struct TextSendOptions {
    pub created_at: u32,
    pub client_message_id: u32,
    pub source: Option<String>,
}

/// Persist an accepted account update before it becomes visible to other client
/// operations. Implementations store data only: they must not call back into the
/// client, perform network operations, or implement authentication/retry policy.
/// A failed write leaves in-memory state unchanged and never retries a request.
pub trait AccountPersistence: Send + Sync {
    fn persist(&self, previous: &AccountState, accepted: &AccountState) -> Result<()>;
}

/// A verified response could not commit its account update. The response may
/// still be retained independently; this error never authorizes resubmission.
#[derive(Debug)]
pub struct AccountPersistenceFailed;
impl std::fmt::Display for AccountPersistenceFailed {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Accepted account update could not be persisted")
    }
}
impl std::error::Error for AccountPersistenceFailed {}

/// One reserved terminal operation. Reservation stops account admission without
/// sending anything. An embedding daemon can commit local logout inhibition
/// before consuming this token to submit its optional remote logout.
/// Dropping the token leaves the account stopped and sends no request.
pub struct PendingLogout {
    exchange: Arc<Exchange>,
    state: AccountState,
    options: NativeOptions,
}

impl PendingLogout {
    /// Wait for requests admitted before the reservation, then submit the logout
    /// once on Tokio's blocking pool.
    pub async fn submit(self) -> Result<super::LogoutReply> {
        self.submit_guarded(|| Ok(())).await
    }

    /// Recheck the embedding application's committed logout operation immediately
    /// before business handoff. This token is consumed even on failure; neither
    /// a cancelled waiter nor an uncertain response permits automatic resubmission.
    pub async fn submit_guarded<F>(self, before_submit: F) -> Result<super::LogoutReply>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        self.exchange.account.drain_to(1).await?;
        let cancellation = Arc::new(AtomicBool::new(false));
        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
        tokio::task::spawn_blocking(move || self.submit_on_worker(cancellation, before_submit))
            .await
            .context("Account logout worker failed")?
    }

    /// As [`Self::submit`], on the caller's blocking worker. No Tokio runtime is
    /// needed. Do not call it on an async executor thread or from inside an
    /// account request: it waits for every earlier request to finish.
    pub fn submit_blocking(self) -> Result<super::LogoutReply> {
        self.submit_guarded_blocking(|| Ok(()))
    }

    /// As [`Self::submit_guarded`], on the caller's blocking worker. The token
    /// is consumed even on failure, and an uncertain response never permits
    /// automatic resubmission.
    pub fn submit_guarded_blocking<F>(self, before_submit: F) -> Result<super::LogoutReply>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        self.exchange.account.drain_to_blocking(1)?;
        self.submit_on_worker(Arc::new(AtomicBool::new(false)), before_submit)
    }

    fn submit_on_worker<F>(
        self,
        cancellation: Arc<AtomicBool>,
        before_submit: F,
    ) -> Result<super::LogoutReply>
    where
        F: FnOnce() -> Result<()> + Send + 'static,
    {
        let Self {
            exchange,
            mut state,
            options,
        } = self;
        let mut transport = NativeClient::new(options)?;
        transport.submission_guard = Some(logout_guard(exchange, cancellation, before_submit));
        transport.logout_snapshot(&mut state)
    }
}

/// Final check before the logout bytes are handed to transport. It passes at
/// most once; every refusal is marked as not submitted.
fn logout_guard<F>(
    exchange: Arc<Exchange>,
    cancellation: Arc<AtomicBool>,
    before_submit: F,
) -> Arc<dyn Fn() -> Result<()> + Send + Sync>
where
    F: FnOnce() -> Result<()> + Send + 'static,
{
    let before_submit = Mutex::new(Some(before_submit));
    Arc::new(move || {
        let check = (|| {
            ensure!(
                !cancellation.load(Ordering::Acquire),
                "Account logout cancelled before submission"
            );
            exchange.check_logout()
        })();
        check.map_err(|error| error.context(NativeRequestNotSubmitted))?;
        let guard = before_submit
            .lock()
            .map_err(|_| anyhow::anyhow!("Logout guard unavailable"))?
            .take()
            .context("Logout already submitted")?;
        guard().map_err(|error| error.context(NativeRequestNotSubmitted))
    })
}

pub(super) struct OwnedAccount {
    data: Mutex<AccountData>,
    changed: Notify,
    // Wakes blocking waiters for the same changes as `changed`.
    changed_blocking: Condvar,
    authority: Arc<Authority>,
    components: components::AccountComponents,
}

struct AccountData {
    state: Option<AccountState>,
    revision: u64,
    credential_generation: u64,
    lifecycle: AccountLifecycle,
    in_flight: usize,
    persistence: Option<Arc<dyn AccountPersistence>>,
}

impl AccountData {
    /// Reason a request cannot use this account in its current lifecycle.
    fn interruption(&self) -> AccountInterrupted {
        match self.lifecycle {
            AccountLifecycle::Transferred => AccountInterrupted::Transferred,
            AccountLifecycle::Active | AccountLifecycle::Stopped => AccountInterrupted::Stopped,
        }
    }

    fn ensure_active(&self, message: &'static str) -> Result<()> {
        if self.lifecycle == AccountLifecycle::Active {
            Ok(())
        } else {
            Err(self.interruption().because(message))
        }
    }
}

fn transferred() -> anyhow::Error {
    AccountInterrupted::Transferred.because("Account state transferred")
}

struct Exchange {
    account: Arc<OwnedAccount>,
    revision: u64,
    credential_generation: u64,
    non_cookie: [u8; 32],
}

struct CancelOnDrop(Arc<AtomicBool>);

impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        self.0.store(true, Ordering::Release);
    }
}

impl OwnedAccount {
    fn lock(&self) -> Result<MutexGuard<'_, AccountData>> {
        self.data
            .lock()
            .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))
    }

    /// Call after releasing the data lock, once lifecycle or `in_flight` changed.
    fn notify_changed(&self) {
        self.changed.notify_waiters();
        self.changed_blocking.notify_all();
    }

    fn begin(self: &Arc<Self>) -> Result<(Exchange, AccountState)> {
        self.begin_with_terminal(false)
    }

    fn begin_with_terminal(self: &Arc<Self>, terminal: bool) -> Result<(Exchange, AccountState)> {
        let mut data = self.lock()?;
        if !self.authority.active.load(Ordering::Acquire) {
            return Err(data.interruption().because("Account is stopped"));
        }
        data.ensure_active("Account is stopped")?;
        let state = data.state.as_ref().ok_or_else(transferred)?.clone();
        let non_cookie = non_cookie_digest(&state)?;
        data.in_flight = data
            .in_flight
            .checked_add(1)
            .context("Too many account requests")?;
        let exchange = Exchange {
            account: self.clone(),
            revision: data.revision,
            credential_generation: data.credential_generation,
            non_cookie,
        };
        if terminal {
            data.lifecycle = AccountLifecycle::Stopped;
            self.authority.active.store(false, Ordering::Release);
        }
        drop(data);
        if terminal {
            self.notify_changed();
        }
        Ok((exchange, state))
    }

    fn stop(&self) -> Result<()> {
        self.authority.active.store(false, Ordering::Release);
        {
            let mut data = self.lock()?;
            if data.lifecycle == AccountLifecycle::Active {
                data.lifecycle = AccountLifecycle::Stopped;
            }
        }
        self.notify_changed();
        Ok(())
    }

    async fn stopped(&self) {
        loop {
            let notified = self.changed.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            if !self
                .lock()
                .is_ok_and(|data| data.lifecycle == AccountLifecycle::Active)
            {
                return;
            }
            notified.await;
        }
    }

    async fn stop_and_drain(&self) -> Result<()> {
        self.stop()?;
        self.drain_to(0).await
    }

    async fn drain_to(&self, remaining: usize) -> Result<()> {
        loop {
            let notified = self.changed.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            if self.lock()?.in_flight == remaining {
                return Ok(());
            }
            notified.await;
        }
    }
}

impl OwnedAccount {
    /// Blocking form of `drain_to`. Counts only change under the data lock, so
    /// a waiter cannot miss the wakeup that follows a change.
    fn drain_to_blocking(&self, remaining: usize) -> Result<()> {
        let mut data = self.lock()?;
        while data.in_flight != remaining {
            data = self
                .changed_blocking
                .wait(data)
                .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))?;
        }
        Ok(())
    }

    fn stop_and_drain_blocking(&self) -> Result<()> {
        self.stop()?;
        self.drain_to_blocking(0)
    }
}

impl Exchange {
    fn check_logout(&self) -> Result<()> {
        let data = self.account.lock()?;
        ensure!(
            data.lifecycle == AccountLifecycle::Stopped && data.in_flight == 1,
            "Logout is not the exclusive account operation"
        );
        let current = data.state.as_ref().ok_or_else(transferred)?;
        ensure!(
            data.credential_generation == self.credential_generation
                && non_cookie_digest(current)? == self.non_cookie,
            "Account authentication superseded logout"
        );
        Ok(())
    }
    /// Check immediately before handing business bytes to transport. A request
    /// already handed off cannot be recalled by a later shutdown.
    fn check(&self) -> Result<()> {
        let data = self.account.lock()?;
        data.ensure_active("Account stopped during request")?;
        let current = data.state.as_ref().ok_or_else(transferred)?;
        if data.credential_generation != self.credential_generation
            || non_cookie_digest(current)? != self.non_cookie
        {
            return Err(AccountInterrupted::CredentialsSuperseded
                .because("Account credentials changed during request"));
        }
        Ok(())
    }

    fn accept_cookie(&self, returned: &AccountState) -> Result<()> {
        returned.validate()?;
        ensure!(
            non_cookie_digest(returned)? == self.non_cookie,
            "Unexpected account credential change"
        );
        let mut data = self.account.lock()?;
        data.ensure_active("Account stopped during request")?;
        let current = data.state.as_ref().ok_or_else(transferred)?;
        if data.credential_generation != self.credential_generation
            || non_cookie_digest(current)? != self.non_cookie
        {
            return Err(AccountInterrupted::CredentialsSuperseded
                .because("Account credentials changed during request"));
        }
        // A concurrent response already adopted a newer cookie. Preserve that
        // whole accepted state rather than overwriting it with a stale snapshot.
        if data.revision == self.revision && current.cookie != returned.cookie {
            let revision = data
                .revision
                .checked_add(1)
                .context("Account revision exhausted")?;
            if let Some(storage) = &data.persistence {
                storage
                    .persist(current, returned)
                    .map_err(|error| error.context(AccountPersistenceFailed))?;
            }
            data.state
                .as_mut()
                .ok_or_else(transferred)?
                .cookie
                .clone_from(&returned.cookie);
            data.revision = revision;
        }
        Ok(())
    }

    fn accept_credentials(&self, returned: AccountState) -> Result<()> {
        returned.validate()?;
        let mut data = self.account.lock()?;
        data.ensure_active("Account stopped during authentication")?;
        let current = data.state.as_ref().ok_or_else(transferred)?;
        if data.credential_generation != self.credential_generation
            || non_cookie_digest(current)? != self.non_cookie
        {
            return Err(AccountInterrupted::CredentialsSuperseded
                .because("Account authentication superseded"));
        }
        ensure!(
            current.uin == returned.uin
                && current.own_username == returned.own_username
                && current.device.device_id == returned.device.device_id
                && current.device.device_type == returned.device.device_type
                && current.device.client_version == returned.device.client_version,
            "Account authentication identity mismatch"
        );
        let revision = data
            .revision
            .checked_add(1)
            .context("Account revision exhausted")?;
        let generation = data
            .credential_generation
            .checked_add(1)
            .context("Account credential generation exhausted")?;
        if let Some(storage) = &data.persistence {
            storage
                .persist(current, &returned)
                .map_err(|error| error.context(AccountPersistenceFailed))?;
        }
        data.state = Some(returned);
        data.revision = revision;
        data.credential_generation = generation;
        self.account
            .authority
            .credential_generation
            .store(generation, Ordering::Release);
        Ok(())
    }
}

impl Drop for Exchange {
    fn drop(&mut self) {
        // Release even after a worker panic. Other access still fails closed
        // when the mutex is poisoned; waiters must nevertheless be awakened.
        let mut data = self
            .account
            .data
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        data.in_flight -= 1;
        drop(data);
        self.account.notify_changed();
    }
}

fn non_cookie_digest(state: &AccountState) -> Result<[u8; 32]> {
    let mut without_cookie = state.clone();
    zeroize::Zeroize::zeroize(&mut without_cookie.cookie);
    without_cookie.cookie.clear();
    let encoded = Zeroizing::new(serde_json::to_vec(&without_cookie)?);
    Ok(openssl::sha::sha256(&encoded))
}

impl NativeClient {
    pub(super) fn check_snapshot_transport(&self) -> Result<()> {
        ensure!(
            self.account.is_none(),
            "Explicit-state transport cannot use a bound account client"
        );
        Ok(())
    }

    pub(super) fn check_submission(&self) -> Result<()> {
        if let Some(check) = &self.submission_guard {
            check()?;
        }
        Ok(())
    }
    /// Bind an accepted account to this client. Clones share the same owner;
    /// construction performs no network operation or credential persistence.
    pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self> {
        state.validate()?;
        let mut client = Self::new(options)?;
        client.account = Some(Arc::new(OwnedAccount {
            data: Mutex::new(AccountData {
                state: Some(state),
                revision: 0,
                credential_generation: 0,
                lifecycle: AccountLifecycle::Active,
                in_flight: 0,
                persistence: None,
            }),
            changed: Notify::new(),
            changed_blocking: Condvar::new(),
            authority: Arc::new(Authority {
                active: AtomicBool::new(true),
                credential_generation: AtomicU64::new(0),
            }),
            components: components::AccountComponents::default(),
        }));
        Ok(client)
    }

    /// Use a data-only storage callback for accepted updates. The supplied state
    /// must already be loaded from accepted storage; construction does not write
    /// it back or treat importing bytes as a new authentication acceptance.
    pub fn from_account_with_persistence(
        state: AccountState,
        options: NativeOptions,
        persistence: Arc<dyn AccountPersistence>,
    ) -> Result<Self> {
        let client = Self::from_account(state, options)?;
        client.owned_account()?.lock()?.persistence = Some(persistence);
        Ok(client)
    }

    fn owned_account(&self) -> Result<&Arc<OwnedAccount>> {
        self.account
            .as_ref()
            .context("Native client has no bound account")
    }

    pub fn account_status(&self) -> Result<AccountStatus> {
        let data = self.owned_account()?.lock()?;
        Ok(AccountStatus {
            lifecycle: data.lifecycle,
            revision: data.revision,
            credential_generation: data.credential_generation,
            in_flight: data.in_flight,
        })
    }

    pub fn account_identity(&self) -> Result<AccountIdentity> {
        let data = self.owned_account()?.lock()?;
        let state = data.state.as_ref().ok_or_else(transferred)?;
        Ok(AccountIdentity {
            uin: state.uin,
            own_username: state.own_username.clone(),
        })
    }

    pub fn account_lease(&self) -> Result<AccountLease> {
        let account = self.owned_account()?;
        let data = account.lock()?;
        if !account.authority.active.load(Ordering::Acquire) {
            return Err(data.interruption().because("Account is stopped"));
        }
        data.ensure_active("Account is stopped")?;
        Ok(AccountLease {
            authority: account.authority.clone(),
            credential_generation: data.credential_generation,
        })
    }

    /// Export secret state for persistence. This snapshot does not transfer
    /// ownership or authorize another writer; use quiesce_and_export for handoff.
    pub fn export_account_state(&self) -> Result<AccountState> {
        self.owned_account()?
            .lock()?
            .state
            .as_ref()
            .cloned()
            .ok_or_else(transferred)
    }

    /// Stop account-bound admission and wait for admitted network workers to
    /// finish. Cancelling this future does not reopen admission.
    pub async fn shutdown(&self) -> Result<()> {
        self.owned_account()?.stop_and_drain().await
    }

    /// Fence new submissions immediately. Network requests already handed off
    /// retain their uncertain outcome; shutdown waits for their workers to exit.
    pub fn stop(&self) -> Result<()> {
        self.owned_account()?.stop()
    }

    /// Reserve one terminal operation before the embedding application commits
    /// its own local inhibition. No network work is started by reservation.
    pub fn prepare_logout(&self) -> Result<PendingLogout> {
        let account = self.owned_account()?;
        let (exchange, state) = account
            .begin_with_terminal(true)
            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
        Ok(PendingLogout {
            exchange: Arc::new(exchange),
            state,
            options: self.options.clone(),
        })
    }

    /// Completes when this account owner stops, including through another clone.
    pub async fn stopped(&self) -> Result<()> {
        self.owned_account()?.stopped().await;
        Ok(())
    }

    /// Stop and drain the client, then move its credentials out exactly once.
    /// All cloned handles remain stopped and cannot export the transferred state.
    pub async fn quiesce_and_export(&self) -> Result<AccountState> {
        let account = self.owned_account()?;
        account.stop_and_drain().await?;
        let mut data = account.lock()?;
        let state = data
            .state
            .take()
            .context("Account state already transferred")?;
        data.lifecycle = AccountLifecycle::Transferred;
        Ok(state)
    }

    async fn account_request<T, F>(&self, operation: F) -> Result<T>
    where
        T: Send + 'static,
        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>
            + Send
            + 'static,
    {
        let (exchange, state) = self
            .owned_account()?
            .begin()
            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
        let options = self.options.clone();
        let cancellation = Arc::new(AtomicBool::new(false));
        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
        tokio::task::spawn_blocking(move || {
            Self::execute_account_request(options, exchange, state, cancellation, operation)
        })
        .await
        .context("Account request worker failed")?
    }

    fn account_request_blocking<T, F>(&self, operation: F) -> Result<T>
    where
        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
    {
        let (exchange, state) = self
            .owned_account()?
            .begin()
            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
        Self::execute_account_request(
            self.options.clone(),
            exchange,
            state,
            Arc::new(AtomicBool::new(false)),
            operation,
        )
    }

    fn execute_account_request<T, F>(
        options: NativeOptions,
        exchange: Exchange,
        mut state: AccountState,
        cancellation: Arc<AtomicBool>,
        operation: F,
    ) -> Result<T>
    where
        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
    {
        let exchange = Arc::new(exchange);
        // This transport gets a temporary request snapshot, not another owner.
        let mut transport = NativeClient::new(options)?;
        let submission_exchange = exchange.clone();
        let prior_admission = AtomicBool::new(false);
        transport.submission_guard = Some(Arc::new(move || {
            let check = (|| {
                ensure!(
                    !cancellation.load(Ordering::Acquire),
                    "Account request cancelled before submission"
                );
                submission_exchange.check()
            })();
            match check {
                Ok(()) => {
                    prior_admission.store(true, Ordering::Release);
                    Ok(())
                }
                Err(error) if !prior_admission.load(Ordering::Acquire) => {
                    Err(error.context(NativeRequestNotSubmitted))
                }
                // A logical operation can contain several chunks. Stopping a
                // later chunk never proves the entire operation was unsent.
                Err(error) => Err(error),
            }
        }));
        let result = operation(&transport, &mut state, &|| transport.check_submission());
        // Cookie adoption still follows verified transport when a decoded
        // application result rejects the operation. Preserve original uncertainty.
        let accepted = exchange.accept_cookie(&state);
        match result {
            Ok(value) => {
                accepted?;
                Ok(value)
            }
            Err(error) => match accepted {
                Ok(()) => Err(error),
                Err(account_error) => Err(error.context(account_error)),
            },
        }
    }
}

#[path = "account_request.rs"]
mod request;
pub use request::AccountRequest;

#[path = "account_push.rs"]
mod push;
pub use push::AccountPushConnection;

#[path = "account_operations.rs"]
mod operations;

async fn wait_for_poll<R, C, S>(reply: R, cancellation: C, stopped: S) -> Result<Vec<u8>>
where
    R: Future<Output = Result<Vec<u8>>>,
    C: Future<Output = ()>,
    S: Future<Output = ()>,
{
    tokio::select! {
        biased;
        () = stopped => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
        () = cancellation => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
        result = reply => result,
    }
}

#[cfg(test)]
#[path = "account_tests.rs"]
mod tests;