proofmode 0.9.0

Capture, share, and preserve verifiable photos and videos
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
#[cfg(feature = "wasm")]
mod wasm_tests {
    use proofmode::generate::wasm::{generate_proof_wasm, get_file_hash};
    use std::collections::HashMap;
    use wasm_bindgen::prelude::*;
    use wasm_bindgen_test::*;

    // Mock JavaScript callbacks for testing
    #[wasm_bindgen]
    extern "C" {
        type MockCallbacks;

        #[wasm_bindgen(constructor)]
        fn new() -> MockCallbacks;

        #[wasm_bindgen(method, js_name = getDeviceInfo)]
        fn get_device_info(this: &MockCallbacks) -> JsValue;

        #[wasm_bindgen(method, js_name = getLocationInfo)]
        fn get_location_info(this: &MockCallbacks) -> JsValue;

        #[wasm_bindgen(method, js_name = getNetworkInfo)]
        fn get_network_info(this: &MockCallbacks) -> JsValue;

        #[wasm_bindgen(method, js_name = saveData)]
        fn save_data(this: &MockCallbacks, hash: &str, filename: &str, data: &[u8]) -> bool;

        #[wasm_bindgen(method, js_name = saveText)]
        fn save_text(this: &MockCallbacks, hash: &str, filename: &str, text: &str) -> bool;

        #[wasm_bindgen(method, js_name = signData)]
        fn sign_data(this: &MockCallbacks, data: &[u8]) -> JsValue;

        #[wasm_bindgen(method, js_name = notarizeHash)]
        fn notarize_hash(this: &MockCallbacks, hash: &str) -> JsValue;
    }

    // Test helper to create mock callbacks
    fn create_mock_callbacks() -> JsValue {
        let callbacks = js_sys::Object::new();

        // getDeviceInfo
        let get_device_info = js_sys::Function::new_no_args(
            r#"
            return {
                manufacturer: "TestManufacturer",
                model: "TestModel",
                os_version: "TestOS 1.0",
                device_id: "test-device-123"
            };
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"getDeviceInfo".into(), &get_device_info).unwrap();

        // getLocationInfo
        let get_location_info = js_sys::Function::new_no_args(
            r#"
            return {
                latitude: 40.7128,
                longitude: -74.0060,
                altitude: 10.0,
                accuracy: 5.0,
                provider: "GPS"
            };
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"getLocationInfo".into(), &get_location_info).unwrap();

        // getNetworkInfo
        let get_network_info = js_sys::Function::new_no_args(
            r#"
            return {
                network_type: "WiFi",
                wifi_ssid: "TestNetwork",
                cell_info: null
            };
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"getNetworkInfo".into(), &get_network_info).unwrap();

        // saveData
        let save_data = js_sys::Function::new_with_args(
            "hash, filename, data",
            r#"
            console.log("Saving data:", filename, "for hash:", hash);
            return true;
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"saveData".into(), &save_data).unwrap();

        // saveText
        let save_text = js_sys::Function::new_with_args(
            "hash, filename, text",
            r#"
            console.log("Saving text:", filename, "for hash:", hash);
            return true;
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"saveText".into(), &save_text).unwrap();

        // signData
        let sign_data = js_sys::Function::new_with_args(
            "data",
            r#"
            return null; // No signing in test
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"signData".into(), &sign_data).unwrap();

        // notarizeHash
        let notarize_hash = js_sys::Function::new_with_args(
            "hash",
            r#"
            return null; // No notarization in test
        "#,
        );
        js_sys::Reflect::set(&callbacks, &"notarizeHash".into(), &notarize_hash).unwrap();

        callbacks.into()
    }

    #[wasm_bindgen_test]
    fn test_get_file_hash() {
        let data = b"WASM test data";
        let hash = get_file_hash(data);

        assert_eq!(hash.len(), 64); // SHA256 length
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));

        // Test consistency
        let hash2 = get_file_hash(data);
        assert_eq!(hash, hash2);
    }

    #[wasm_bindgen_test]
    fn test_get_file_hash_different_data() {
        let data1 = b"First data";
        let data2 = b"Second data";

        let hash1 = get_file_hash(data1);
        let hash2 = get_file_hash(data2);

        assert_ne!(hash1, hash2);
    }

    #[wasm_bindgen_test]
    fn test_get_file_hash_empty() {
        let data = b"";
        let hash = get_file_hash(data);

        // SHA256 of empty string
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    // Note: The following tests would require a more complex WASM test setup
    // with proper JavaScript environment and mock objects. They are included
    // as examples of what could be tested in a full WASM test environment.

    /*
    #[wasm_bindgen_test]
    fn test_generate_proof_wasm_basic() {
        let data = b"WASM proof test data";
        let metadata = serde_json::to_string(&HashMap::<String, String>::new()).unwrap();
        let callbacks = create_mock_callbacks();

        let result = generate_proof_wasm(data, &metadata, callbacks);
        assert!(result.is_ok());

        let hash = result.unwrap();
        assert_eq!(hash.len(), 64);

        // Verify hash matches expected
        let expected_hash = get_file_hash(data);
        assert_eq!(hash, expected_hash);
    }

    #[wasm_bindgen_test]
    fn test_generate_proof_wasm_with_metadata() {
        let data = b"WASM proof with metadata";
        let mut metadata_map = HashMap::new();
        metadata_map.insert("description".to_string(), "WASM test description".to_string());
        metadata_map.insert("tags".to_string(), "wasm,test".to_string());
        let metadata = serde_json::to_string(&metadata_map).unwrap();
        let callbacks = create_mock_callbacks();

        let result = generate_proof_wasm(data, &metadata, callbacks);
        assert!(result.is_ok());
    }

    #[wasm_bindgen_test]
    fn test_generate_proof_wasm_invalid_metadata() {
        let data = b"WASM test data";
        let invalid_metadata = "invalid json";
        let callbacks = create_mock_callbacks();

        let result = generate_proof_wasm(data, invalid_metadata, callbacks);
        assert!(result.is_err());
    }
    */
}

// Tests that run in standard Rust test environment
#[cfg(test)]
mod wasm_unit_tests {
    use proofmode::crypto::hash::calculate_hash;

    #[test]
    fn test_hash_function_wasm_compatibility() {
        // Test that our hash function works consistently across platforms
        let test_cases = vec![
            (
                "".as_bytes(),
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            ),
            (
                "a".as_bytes(),
                "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb",
            ),
            (
                "abc".as_bytes(),
                "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
            ),
            (
                "Hello, World!".as_bytes(),
                "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f",
            ),
        ];

        for (input, expected) in test_cases {
            let hash = calculate_hash(input);
            assert_eq!(
                hash,
                expected,
                "Hash mismatch for input: {:?}",
                std::str::from_utf8(input)
            );
        }
    }

    #[test]
    fn test_wasm_compatible_data_structures() {
        use chrono::Utc;
        use proofmode::generate_types::*;
        use std::collections::HashMap;

        // Test that our data structures can be serialized (important for WASM)
        let device_data = DeviceData {
            manufacturer: "Test".to_string(),
            model: "Device".to_string(),
            os_version: "1.0".to_string(),
            device_id: Some("test123".to_string()),
        };

        let location_data = LocationData {
            latitude: 40.7128,
            longitude: -74.0060,
            altitude: Some(10.0),
            accuracy: Some(5.0),
            provider: Some("GPS".to_string()),
        };

        let network_data = NetworkData {
            network_type: "WiFi".to_string(),
            wifi_ssid: Some("TestNetwork".to_string()),
            cell_info: None,
        };

        let proof_data = ProofData {
            file_hash_sha256: "test_hash".to_string(),
            metadata: HashMap::new(),
            location: Some(location_data),
            device: Some(device_data),
            network: Some(network_data),
            timestamps: TimestampData {
                created_at: Utc::now(),
                modified_at: None,
                proof_generated_at: Utc::now(),
            },
            signature: None,
            notarization: None,
        };

        // Should be able to serialize to JSON
        let json = serde_json::to_string(&proof_data);
        assert!(json.is_ok());

        // Should be able to deserialize back
        let deserialized: Result<ProofData, _> = serde_json::from_str(&json.unwrap());
        assert!(deserialized.is_ok());
    }

    #[test]
    fn test_error_types_wasm_compatibility() {
        use proofmode::generate_error::ProofModeError;

        // Test that our error types work across platforms
        let errors = vec![
            ProofModeError::Io("IO error".to_string()),
            ProofModeError::Serialization("Serialization error".to_string()),
            ProofModeError::Crypto("Crypto error".to_string()),
            ProofModeError::Storage("Storage error".to_string()),
        ];

        for error in errors {
            let error_string = error.to_string();
            assert!(!error_string.is_empty());
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_wasm_feature_compilation() {
        // This test only runs when WASM feature is enabled
        // Ensures WASM-specific code compiles

        // Test that WASM modules can be imported
        use proofmode::generate::wasm::get_file_hash;

        let hash = get_file_hash(b"test");
        assert_eq!(hash.len(), 64);
    }

    #[test]
    fn test_platform_agnostic_core() {
        use proofmode::generate::core::{PlatformCallbacks, ProofGenerator};
        use proofmode::generate_types::*;
        use std::collections::HashMap;

        // Mock callbacks that work in any environment
        struct TestCallbacks;

        impl PlatformCallbacks for TestCallbacks {
            fn get_device_info(&self) -> Option<DeviceData> {
                Some(DeviceData {
                    manufacturer: "TestManufacturer".to_string(),
                    model: "TestModel".to_string(),
                    os_version: "TestOS".to_string(),
                    device_id: None,
                })
            }

            fn get_location_info(&self) -> Option<LocationData> {
                None
            }

            fn get_network_info(&self) -> Option<NetworkData> {
                None
            }

            fn save_data(
                &self,
                _hash: &str,
                _filename: &str,
                _data: &[u8],
            ) -> proofmode::generate_error::Result<()> {
                Ok(())
            }

            fn save_text(
                &self,
                _hash: &str,
                _filename: &str,
                _text: &str,
            ) -> proofmode::generate_error::Result<()> {
                Ok(())
            }

            fn sign_data(
                &self,
                _data: &[u8],
            ) -> proofmode::generate_error::Result<Option<Vec<u8>>> {
                Ok(None)
            }

            fn notarize_hash(
                &self,
                _hash: &str,
            ) -> proofmode::generate_error::Result<Option<NotarizationData>> {
                Ok(None)
            }

            fn report_progress(&self, _message: &str) {}
        }

        let config = ProofModeConfig {
            auto_notarize: false,
            track_location: false,
            track_device_id: true,
            track_network: false,
            add_credentials: false,
            embed_c2pa: false,
        };

        let generator = ProofGenerator::new(config);
        let callbacks = TestCallbacks;
        let data = b"platform agnostic test";
        let metadata = HashMap::new();

        let result = generator.generate_proof(data, metadata, &callbacks);
        assert!(result.is_ok());

        let hash = result.unwrap();
        assert_eq!(hash, calculate_hash(data));
    }
}