snarkify-sdk 0.1.0-alpha.11

Snarkify Rust SDK for Streamlined Serverless Prover Development and Deployment
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
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use cloudevents::{AttributesReader, Data, Event, EventBuilder, EventBuilderV10};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use tracing::*;

use crate::datetime_serde::default_dt_formatter;

pub const READ_INPUT_FROM_URL_HEADER: &str = "ce-inputurl";

enum ProofStatus {
    Success = 2,
    Failure = 3,
}

#[derive(Serialize, Deserialize)]
struct ProofResponse {
    task_id: String,
    result: String,
    status: u8,
    #[serde(with = "default_dt_formatter")]
    started: DateTime<Utc>,
    #[serde(with = "default_dt_formatter")]
    finished: DateTime<Utc>,
}

#[async_trait]
pub trait ProofHandler {
    type Input: DeserializeOwned + Send + 'static;
    type Output: Serialize + Send + 'static;
    type Error: Serialize + Send + 'static;

    async fn prove(data: Self::Input) -> Result<Self::Output, Self::Error>;

    #[instrument(skip(event), fields(task_id = event.id()))] // Handle span fields
    async fn handle(event: Event) -> Result<Event, actix_web::Error> {
        let started = Utc::now();
        trace!("Start time {started}");

        let input_url = event.extension(READ_INPUT_FROM_URL_HEADER);
        let result_with_input = match input_url {
            Some(url) => {
                // Get input from URL if provided
                let url_str = url.to_string();
                match reqwest::get(&url_str).await {
                    Ok(response) => match response.text().await {
                        Ok(text) => serde_json::from_str::<Self::Input>(&text).map_err(|err| {
                            format!("Failed to parse JSON from prover input URL: {url_str}; err: {err:?}")
                        }),
                        Err(err) => Err(format!(
                            "Failed to read HTTP response body from prover input URL: {url_str}. Error: {err:?}",
                        )),
                    },
                    Err(err) => Err(format!(
                        "Failed to fetch prover input from URL: {url_str}. Network error: {err:?}",
                    )),
                }
            }
            None => {
                // Use event data if no URL provided
                event
                    .data()
                    .ok_or("Event payload is missing".to_string())
                    .and_then(|data| {
                        match data {
                            Data::Binary(v) => serde_json::from_slice(v),
                            Data::String(v) => serde_json::from_str(v),
                            Data::Json(v) => serde_json::from_value(v.clone()),
                        }
                        .map_err(|err| format!("Failed to parse Json from event payload. Error: {err:?}"))
                    })
            }
        };

        let (result, status) = match result_with_input {
            Ok(input) => {
                // Spawn the async task
                let info_span = info_span!("prove");
                let result = tokio::spawn(async move { Self::prove(input).instrument(info_span).await }).await;
                match result {
                    Ok(prove_result) => match prove_result {
                        Ok(proof) => (
                            serde_json::to_string(&proof).map_err(|err| {
                                error!("Error while serializing success output: {err:?}");
                                err
                            })?,
                            ProofStatus::Success,
                        ),
                        Err(error) => (
                            serde_json::to_string(&error).map_err(|err| {
                                error!("Error while serializing prove error: {err:?}");
                                err
                            })?,
                            ProofStatus::Failure,
                        ),
                    },
                    Err(err) => match err.try_into_panic() {
                        Ok(panic) => {
                            let panic_message = panic
                                .downcast_ref::<String>()
                                .map(|s| s.as_str())
                                .or_else(|| panic.downcast_ref::<&str>().copied())
                                .unwrap_or("A panic occurred during proof.");
                            (panic_message.to_string(), ProofStatus::Failure)
                        }
                        Err(join_err) => (
                            format!("Unexpected error while waiting for proof: {join_err:?}"),
                            ProofStatus::Failure,
                        ),
                    },
                }
            }
            Err(handle_request_err) => {
                error!(handle_request_err);
                // Initial JSON deserialization error
                (handle_request_err.to_string(), ProofStatus::Failure)
            }
        };

        let response = serde_json::to_value(ProofResponse {
            task_id: event.id().to_string(),
            result,
            status: status as u8,
            started,
            finished: Utc::now(),
        })?;

        // events are routed to the right prover through the event.ty() attribute,
        // which is the prover id
        let source = format!("prover-{}", event.ty());
        EventBuilderV10::new()
            .id(event.id())
            .source(source)
            .ty("tenant-service-result") // Be careful of changing this, this is used as filter for backend service
            .data("application/json", response)
            .build()
            .map_err(actix_web::error::ErrorInternalServerError)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mockito::Server;
    use serde_json::json;

    struct MyHandler {}
    struct MyHandlerWithPanic {}

    #[derive(Deserialize)]
    struct MyInput {
        name: String,
    }

    #[derive(Serialize)]
    struct MyOutput {
        result: String,
    }

    #[async_trait]
    impl ProofHandler for MyHandler {
        type Input = MyInput;
        type Output = MyOutput;
        type Error = String;
        async fn prove(data: MyInput) -> Result<MyOutput, String> {
            Ok(MyOutput { result: data.name })
        }
    }

    #[async_trait]
    impl ProofHandler for MyHandlerWithPanic {
        type Input = MyInput;
        type Output = MyOutput;
        type Error = ();
        async fn prove(_data: MyInput) -> Result<MyOutput, ()> {
            panic!("Houston, we have a problem")
        }
    }

    fn get_payload(event: Event) -> ProofResponse {
        if let Some(Data::Json(v)) = event.data() {
            serde_json::from_value::<ProofResponse>(v.clone()).unwrap()
        } else {
            panic!("Expected JSON data in the event.");
        }
    }

    #[actix_rt::test]
    async fn test_prover_handles_valid_event() {
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .data("application/json", json!({"name": "aloha"}))
            .build()
            .unwrap();
        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let event = result.unwrap();
        // Check some properties of the returned event, e.g.:
        assert_eq!(event.source().to_string(), "prover-12345678");
        assert_eq!(event.ty().to_string(), "tenant-service-result");

        let response = get_payload(event);
        assert_eq!(response.status, ProofStatus::Success as u8);
        assert_eq!(response.result, "{\"result\":\"aloha\"}");
    }

    #[actix_rt::test]
    async fn test_prover_handles_event_wrong_input() {
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .data("application/json", json!({"wrong_key": "aloha"}))
            .ty("test.type")
            .build()
            .unwrap();
        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(response.result.contains("missing field `name`"));
    }

    #[actix_rt::test]
    async fn test_prover_handles_event_missing_input() {
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("test.type")
            .build()
            .unwrap();
        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(response.result.contains("Event payload is missing"));
    }

    #[actix_rt::test]
    async fn test_prover_handles_invalid_json_input() {
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .data("application/json", "invalid json {") // Invalid JSON string
            .ty("test.type")
            .build()
            .unwrap();
        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(
            response.result.contains("Failed to parse Json from event payload"),
            "Expected JSON parsing error message, got: {}",
            response.result
        );
    }

    #[actix_rt::test]
    async fn test_prover_handles_panic() {
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .data("application/json", json!({"name": "aloha"}))
            .build()
            .unwrap();
        let result = MyHandlerWithPanic::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert_eq!(response.result, "Houston, we have a problem");
    }

    #[actix_rt::test]
    async fn test_prover_handles_url_input() {
        // Create the mock server in a separate thread to avoid runtime conflicts
        let server = std::thread::spawn(|| {
            let mut server = Server::new();
            let mock = server
                .mock("GET", "/input")
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(r#"{"name": "from_url"}"#)
                .expect(1)
                .create();

            (server, mock)
        })
        .join()
        .unwrap();

        let test_url = format!("{}/input", server.0.url());
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .extension(READ_INPUT_FROM_URL_HEADER, test_url)
            .build()
            .unwrap();

        let result = MyHandler::handle(mock_event).await;

        assert!(result.is_ok());
        let event = result.unwrap();
        assert_eq!(event.source().to_string(), "prover-12345678");
        assert_eq!(event.ty().to_string(), "tenant-service-result");

        let response = get_payload(event);
        assert_eq!(response.status, ProofStatus::Success as u8);
        assert_eq!(response.result, "{\"result\":\"from_url\"}");

        // Verify that the mock was called
        server.1.assert();
    }

    #[actix_rt::test]
    async fn test_prover_handles_url_fetch_failure() {
        let test_url = "http://localhost:12345/nonexistent";
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .extension(READ_INPUT_FROM_URL_HEADER, test_url)
            .build()
            .unwrap();

        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok(), "Handler should return Ok even for URL fetch failures");

        let event = result.unwrap();
        let response = get_payload(event);
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(
            response.result.contains("Failed to fetch prover input from URL")
                && response.result.contains("Network error")
                && response.result.contains(test_url),
            "Expected detailed error message about URL fetch failure, got: {}",
            response.result
        );
    }

    #[actix_rt::test]
    async fn test_prover_handles_url_invalid_json() {
        let server = std::thread::spawn(|| {
            let mut server = Server::new();
            let mock = server
                .mock("GET", "/invalid-json")
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(r#"{"invalid json format"#)
                .expect(1)
                .create();

            (server, mock)
        })
        .join()
        .unwrap();

        let test_url = format!("{}/invalid-json", server.0.url());
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .extension(READ_INPUT_FROM_URL_HEADER, test_url.clone())
            .build()
            .unwrap();

        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(
            response.result.contains("Failed to parse JSON from prover input URL")
                && response.result.contains(&test_url),
            "Expected detailed error about JSON parsing failure, got: {}",
            response.result
        );

        server.1.assert();
    }

    #[actix_rt::test]
    async fn test_prover_handles_url_wrong_json_schema() {
        let server = std::thread::spawn(|| {
            let mut server = Server::new();
            let mock = server
                .mock("GET", "/wrong-schema")
                .with_status(200)
                .with_header("content-type", "application/json")
                .with_body(r#"{"wrong_field": "value"}"#) // Valid JSON but wrong schema
                .expect(1)
                .create();

            (server, mock)
        })
        .join()
        .unwrap();

        let test_url = format!("{}/wrong-schema", server.0.url());
        let mock_event = EventBuilderV10::new()
            .id("test_id")
            .source("test://source")
            .ty("12345678")
            .extension(READ_INPUT_FROM_URL_HEADER, test_url)
            .build()
            .unwrap();

        let result = MyHandler::handle(mock_event).await;
        assert!(result.is_ok());

        let response = get_payload(result.unwrap());
        assert_eq!(response.status, ProofStatus::Failure as u8);
        assert!(response.result.contains("missing field `name`"));

        server.1.assert();
    }
}