guardian-client 0.17.0

Client library for Guardian
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
use crate::proto::guardian_server::{Guardian, GuardianServer};
use crate::proto::{
    AbandonDeltaCandidateRequest, AbandonDeltaCandidateResponse, AccountState, ConfigureRequest,
    ConfigureResponse, DeltaObject as ProtoDeltaObject, GetAccountByKeyCommitmentRequest,
    GetAccountByKeyCommitmentResponse, GetDeltaHistoryRequest, GetDeltaHistoryResponse,
    GetDeltaProposalRequest, GetDeltaProposalResponse, GetDeltaProposalsRequest,
    GetDeltaProposalsResponse, GetDeltaRequest, GetDeltaResponse, GetDeltaSinceRequest,
    GetDeltaSinceResponse, GetPubkeyRequest, GetStateRequest, GetStateResponse,
    PushDeltaProposalRequest, PushDeltaProposalResponse, PushDeltaRequest, PushDeltaResponse,
    SignDeltaProposalRequest, SignDeltaProposalResponse,
};
use std::net::SocketAddr;
use std::sync::{Arc, Mutex as StdMutex};
use tonic::transport::Server;
use tonic::{Request, Response, Status};

/// Post-start control surface for a [`MockGuardianService`]: the service is
/// moved into `start_mock_server`, so tests clone a handle first to observe
/// recorded traffic and to (re)arm responses while the server runs.
///
/// Persistent responses complement the one-shot `with_*` builders: a
/// persistent response is served whenever no one-shot response is queued for
/// that endpoint, instead of the endpoint's hardcoded default — so multi-call
/// flows (sync loops, repeated listings) can run against stable data.
#[derive(Clone, Default)]
pub struct MockGuardianHandle {
    /// Guardian method names in arrival order, across all endpoints that
    /// record themselves — the cross-endpoint ordering log.
    calls: Arc<StdMutex<Vec<String>>>,
    /// Every `push_delta_proposal` request body, in arrival order.
    push_delta_proposal_requests: Arc<StdMutex<Vec<PushDeltaProposalRequest>>>,
    persistent_get_pubkey: Arc<StdMutex<Option<String>>>,
    persistent_get_state: Arc<StdMutex<Option<GetStateResponse>>>,
    persistent_get_delta_proposal: Arc<StdMutex<Option<GetDeltaProposalResponse>>>,
    persistent_get_delta_proposals: Arc<StdMutex<Option<GetDeltaProposalsResponse>>>,
}

impl MockGuardianHandle {
    /// Guardian method names in arrival order.
    pub fn calls(&self) -> Vec<String> {
        self.calls.lock().unwrap().clone()
    }

    /// Every `push_delta_proposal` request received so far.
    pub fn pushed_proposals(&self) -> Vec<PushDeltaProposalRequest> {
        self.push_delta_proposal_requests.lock().unwrap().clone()
    }

    /// Serve `pubkey` from `get_pubkey` whenever no one-shot response is queued.
    pub fn set_persistent_get_pubkey(&self, pubkey: impl Into<String>) {
        *self.persistent_get_pubkey.lock().unwrap() = Some(pubkey.into());
    }

    /// Serve `response` from `get_state` whenever the one-shot queue is empty.
    pub fn set_persistent_get_state(&self, response: GetStateResponse) {
        *self.persistent_get_state.lock().unwrap() = Some(response);
    }

    /// Serve `response` from `get_delta_proposal` whenever no one-shot response is queued.
    pub fn set_persistent_get_delta_proposal(&self, response: GetDeltaProposalResponse) {
        *self.persistent_get_delta_proposal.lock().unwrap() = Some(response);
    }

    /// Serve `response` from `get_delta_proposals` whenever no one-shot response is queued.
    pub fn set_persistent_get_delta_proposals(&self, response: GetDeltaProposalsResponse) {
        *self.persistent_get_delta_proposals.lock().unwrap() = Some(response);
    }
}

#[derive(Default)]
pub struct MockGuardianService {
    handle: MockGuardianHandle,
    get_pubkey_response: Arc<StdMutex<Option<Result<String, Status>>>>,
    configure_response: Arc<StdMutex<Option<Result<ConfigureResponse, Status>>>>,
    push_delta_proposal_response: Arc<StdMutex<Option<Result<PushDeltaProposalResponse, Status>>>>,
    get_delta_proposal_response: Arc<StdMutex<Option<Result<GetDeltaProposalResponse, Status>>>>,
    get_delta_proposals_response: Arc<StdMutex<Option<Result<GetDeltaProposalsResponse, Status>>>>,
    sign_delta_proposal_response: Arc<StdMutex<Option<Result<SignDeltaProposalResponse, Status>>>>,
    push_delta_response: Arc<StdMutex<Option<Result<PushDeltaResponse, Status>>>>,
    get_delta_response: Arc<StdMutex<Option<Result<GetDeltaResponse, Status>>>>,
    get_delta_since_response: Arc<StdMutex<Option<Result<GetDeltaSinceResponse, Status>>>>,
    get_delta_history_response: Arc<StdMutex<Option<Result<GetDeltaHistoryResponse, Status>>>>,
    get_delta_history_requests: Arc<StdMutex<Vec<(GetDeltaHistoryRequest, i64, String)>>>,
    get_state_responses: Arc<StdMutex<Vec<Result<GetStateResponse, Status>>>>,
    get_state_auth_headers: Arc<StdMutex<Vec<(i64, String)>>>,
    get_account_by_key_commitment_response:
        Arc<StdMutex<Option<Result<GetAccountByKeyCommitmentResponse, Status>>>>,
    abandon_delta_candidate_response:
        Arc<StdMutex<Option<Result<AbandonDeltaCandidateResponse, Status>>>>,
}

impl MockGuardianService {
    pub fn with_get_pubkey(self, response: Result<String, Status>) -> Self {
        *self.get_pubkey_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_configure(self, response: Result<ConfigureResponse, Status>) -> Self {
        *self.configure_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_get_delta_history(self, response: Result<GetDeltaHistoryResponse, Status>) -> Self {
        *self.get_delta_history_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_push_delta_proposal(
        self,
        response: Result<PushDeltaProposalResponse, Status>,
    ) -> Self {
        *self.push_delta_proposal_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_get_delta_proposals(
        self,
        response: Result<GetDeltaProposalsResponse, Status>,
    ) -> Self {
        *self.get_delta_proposals_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_get_delta_proposal(
        self,
        response: Result<GetDeltaProposalResponse, Status>,
    ) -> Self {
        *self.get_delta_proposal_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_sign_delta_proposal(
        self,
        response: Result<SignDeltaProposalResponse, Status>,
    ) -> Self {
        *self.sign_delta_proposal_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_push_delta(self, response: Result<PushDeltaResponse, Status>) -> Self {
        *self.push_delta_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_get_delta(self, response: Result<GetDeltaResponse, Status>) -> Self {
        *self.get_delta_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_get_delta_since(self, response: Result<GetDeltaSinceResponse, Status>) -> Self {
        *self.get_delta_since_response.lock().unwrap() = Some(response);
        self
    }

    /// Queue a `get_state` response. Responses are served FIFO; once the
    /// queue is empty the handler falls back to its default success, so
    /// queueing N errors makes attempt N+1 succeed.
    pub fn with_get_state(self, response: Result<GetStateResponse, Status>) -> Self {
        self.get_state_responses.lock().unwrap().push(response);
        self
    }

    /// Handle onto the `(x-timestamp, x-signature)` pairs recorded from every
    /// `get_state` request, in arrival order. Clone before moving the service
    /// into `start_mock_server` to observe per-attempt auth metadata.
    pub fn get_state_auth_headers_handle(&self) -> Arc<StdMutex<Vec<(i64, String)>>> {
        self.get_state_auth_headers.clone()
    }

    /// Requests seen by `get_delta_history`, each with the
    /// `x-timestamp` and `x-signature` metadata it carried, so tests
    /// can assert the outgoing message and auth instead of only the
    /// response mapping.
    pub fn get_delta_history_requests_handle(
        &self,
    ) -> Arc<StdMutex<Vec<(GetDeltaHistoryRequest, i64, String)>>> {
        self.get_delta_history_requests.clone()
    }

    pub fn with_get_account_by_key_commitment(
        self,
        response: Result<GetAccountByKeyCommitmentResponse, Status>,
    ) -> Self {
        *self.get_account_by_key_commitment_response.lock().unwrap() = Some(response);
        self
    }

    pub fn with_abandon_delta_candidate(
        self,
        response: Result<AbandonDeltaCandidateResponse, Status>,
    ) -> Self {
        *self.abandon_delta_candidate_response.lock().unwrap() = Some(response);
        self
    }

    /// Clone the post-start control surface before moving the service into
    /// [`start_mock_server`]. See [`MockGuardianHandle`].
    pub fn handle(&self) -> MockGuardianHandle {
        self.handle.clone()
    }

    fn record_call(&self, method: &str) {
        self.handle.calls.lock().unwrap().push(method.to_string());
    }
}

/// Shared precedence for endpoints with a persistent slot: the armed
/// persistent response if any, otherwise the endpoint's hardcoded default.
/// (Callers apply this only after the one-shot queue came up empty, so the
/// full order is: one-shot, then persistent, then default.)
fn persistent_or<T: Clone>(slot: &StdMutex<Option<T>>, default: impl FnOnce() -> T) -> T {
    slot.lock().unwrap().clone().unwrap_or_else(default)
}

#[tonic::async_trait]
impl Guardian for MockGuardianService {
    async fn get_pubkey(
        &self,
        _request: Request<GetPubkeyRequest>,
    ) -> Result<Response<crate::proto::GetPubkeyResponse>, Status> {
        self.record_call("get_pubkey");
        let response = self
            .get_pubkey_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(persistent_or(&self.handle.persistent_get_pubkey, || {
                    "mock_pubkey".to_string()
                }))
            });

        response.map(|pubkey| {
            Response::new(crate::proto::GetPubkeyResponse {
                pubkey,
                raw_pubkey: None,
            })
        })
    }

    async fn configure(
        &self,
        _request: Request<ConfigureRequest>,
    ) -> Result<Response<ConfigureResponse>, Status> {
        self.record_call("configure");
        let response = self
            .configure_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(ConfigureResponse {
                    success: true,
                    message: String::new(),
                    ack_pubkey: "mock_ack_pubkey".to_string(),
                    ack_commitment: String::new(),
                })
            });

        response.map(Response::new)
    }

    async fn push_delta_proposal(
        &self,
        request: Request<PushDeltaProposalRequest>,
    ) -> Result<Response<PushDeltaProposalResponse>, Status> {
        self.record_call("push_delta_proposal");
        self.handle
            .push_delta_proposal_requests
            .lock()
            .unwrap()
            .push(request.into_inner());
        let response = self
            .push_delta_proposal_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(PushDeltaProposalResponse {
                    success: true,
                    message: String::new(),
                    commitment: "mock_commitment".to_string(),
                    delta: Some(create_mock_delta()),
                })
            });

        response.map(Response::new)
    }

    async fn get_delta_proposals(
        &self,
        _request: Request<GetDeltaProposalsRequest>,
    ) -> Result<Response<GetDeltaProposalsResponse>, Status> {
        self.record_call("get_delta_proposals");
        let response = self
            .get_delta_proposals_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(persistent_or(
                    &self.handle.persistent_get_delta_proposals,
                    || GetDeltaProposalsResponse {
                        success: true,
                        message: String::new(),
                        proposals: vec![],
                    },
                ))
            });

        response.map(Response::new)
    }

    async fn get_delta_proposal(
        &self,
        _request: Request<GetDeltaProposalRequest>,
    ) -> Result<Response<GetDeltaProposalResponse>, Status> {
        self.record_call("get_delta_proposal");
        let response = self
            .get_delta_proposal_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(persistent_or(
                    &self.handle.persistent_get_delta_proposal,
                    || GetDeltaProposalResponse {
                        success: true,
                        message: String::new(),
                        proposal: Some(create_mock_delta()),
                    },
                ))
            });

        response.map(Response::new)
    }

    async fn sign_delta_proposal(
        &self,
        _request: Request<SignDeltaProposalRequest>,
    ) -> Result<Response<SignDeltaProposalResponse>, Status> {
        let response = self
            .sign_delta_proposal_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(SignDeltaProposalResponse {
                    success: true,
                    message: String::new(),
                    delta: Some(create_mock_delta()),
                })
            });

        response.map(Response::new)
    }

    async fn abandon_delta_candidate(
        &self,
        request: Request<AbandonDeltaCandidateRequest>,
    ) -> Result<Response<AbandonDeltaCandidateResponse>, Status> {
        let data = request.into_inner();
        let response = self
            .abandon_delta_candidate_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(AbandonDeltaCandidateResponse {
                    success: true,
                    message: String::new(),
                    account_id: data.account_id,
                    nonce: data.nonce,
                    state: "pending".to_string(),
                    abandon_requested_at: "2026-07-14T12:00:00Z".to_string(),
                    error_code: String::new(),
                })
            });

        response.map(Response::new)
    }

    async fn push_delta(
        &self,
        _request: Request<PushDeltaRequest>,
    ) -> Result<Response<PushDeltaResponse>, Status> {
        self.record_call("push_delta");
        let response = self
            .push_delta_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(PushDeltaResponse {
                    success: true,
                    message: String::new(),
                    delta: Some(create_mock_delta()),
                    ack_sig: None,
                })
            });

        response.map(Response::new)
    }

    async fn get_delta(
        &self,
        _request: Request<GetDeltaRequest>,
    ) -> Result<Response<GetDeltaResponse>, Status> {
        let response = self
            .get_delta_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(GetDeltaResponse {
                    success: true,
                    message: String::new(),
                    delta: Some(create_mock_delta()),
                })
            });

        response.map(Response::new)
    }

    async fn get_delta_since(
        &self,
        _request: Request<GetDeltaSinceRequest>,
    ) -> Result<Response<GetDeltaSinceResponse>, Status> {
        let response = self
            .get_delta_since_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(GetDeltaSinceResponse {
                    success: true,
                    message: String::new(),
                    merged_delta: Some(create_mock_delta()),
                })
            });

        response.map(Response::new)
    }

    async fn get_delta_history(
        &self,
        request: Request<GetDeltaHistoryRequest>,
    ) -> Result<Response<GetDeltaHistoryResponse>, Status> {
        let timestamp = request
            .metadata()
            .get("x-timestamp")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<i64>().ok())
            .unwrap_or_default();
        let signature = request
            .metadata()
            .get("x-signature")
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_string();
        self.get_delta_history_requests.lock().unwrap().push((
            request.get_ref().clone(),
            timestamp,
            signature,
        ));

        let response = self
            .get_delta_history_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| {
                Ok(GetDeltaHistoryResponse {
                    success: true,
                    message: String::new(),
                    entries: Vec::new(),
                    next_cursor: None,
                })
            });

        response.map(Response::new)
    }

    async fn get_state(
        &self,
        request: Request<GetStateRequest>,
    ) -> Result<Response<GetStateResponse>, Status> {
        let timestamp = request
            .metadata()
            .get("x-timestamp")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<i64>().ok())
            .unwrap_or_default();
        let signature = request
            .metadata()
            .get("x-signature")
            .and_then(|value| value.to_str().ok())
            .unwrap_or_default()
            .to_string();
        self.get_state_auth_headers
            .lock()
            .unwrap()
            .push((timestamp, signature));

        self.record_call("get_state");
        let mut responses = self.get_state_responses.lock().unwrap();
        let response = if responses.is_empty() {
            Ok(persistent_or(&self.handle.persistent_get_state, || {
                GetStateResponse {
                    success: true,
                    message: String::new(),
                    state: Some(create_mock_account_state()),
                }
            }))
        } else {
            responses.remove(0)
        };

        response.map(Response::new)
    }

    async fn get_account_by_key_commitment(
        &self,
        _request: Request<GetAccountByKeyCommitmentRequest>,
    ) -> Result<Response<GetAccountByKeyCommitmentResponse>, Status> {
        let response = self
            .get_account_by_key_commitment_response
            .lock()
            .unwrap()
            .take()
            .unwrap_or_else(|| Ok(GetAccountByKeyCommitmentResponse { accounts: vec![] }));

        response.map(Response::new)
    }
}

pub async fn start_mock_server(
    service: MockGuardianService,
) -> Result<String, Box<dyn std::error::Error>> {
    let addr: SocketAddr = "127.0.0.1:0".parse()?;
    let listener = tokio::net::TcpListener::bind(addr).await?;
    let local_addr = listener.local_addr()?;
    let endpoint = format!("http://{}", local_addr);

    tokio::spawn(async move {
        Server::builder()
            .add_service(GuardianServer::new(service))
            .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))
            .await
            .ok();
    });

    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

    Ok(endpoint)
}

pub fn create_mock_delta() -> ProtoDeltaObject {
    ProtoDeltaObject {
        account_id: "0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b".to_string(),
        nonce: 1,
        prev_commitment: "0x123".to_string(),
        delta_payload: r#"{"updates": []}"#.to_string(),
        new_commitment: "0x456".to_string(),
        ack_sig: String::new(),
        candidate_at: String::new(),
        canonical_at: None,
        discarded_at: None,
        status: None,
        ack_pubkey: None,
        ack_scheme: None,
    }
}

pub fn create_mock_account_state() -> AccountState {
    AccountState {
        account_id: "0x7b7b7b7a7b7b7b017b7b7b7b7b7b7b".to_string(),
        state_json: r#"{"balance": 1000}"#.to_string(),
        commitment: "0x123".to_string(),
        created_at: "2024-01-01T00:00:00Z".to_string(),
        updated_at: "2024-01-01T00:00:00Z".to_string(),
    }
}