freenet 0.2.48

Freenet core software
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
//! Edge case tests for contract state size boundaries
//!
//! Tests boundary conditions for contract state sizes:
//! - Minimal states (empty, near-zero bytes)
//! - Large states (approaching 1MB)
//! - Maximum allowed states
//!
//! These tests validate that the system correctly handles edge cases in contract state sizes.

use freenet::test_utils::{
    Task, TestContext, TodoList, create_large_todo_list, create_minimal_state,
    create_oversized_todo_list, load_contract, make_get, make_put, make_update,
};
use freenet_macros::freenet_test;
use freenet_stdlib::{
    client_api::{ClientRequest, ContractResponse, HostResponse, WebApi},
    prelude::*,
};
use std::time::Duration;
use tokio::time::timeout;
use tokio_tungstenite::connect_async;

/// Test that minimal states can be stored and retrieved
///
/// Verifies the lower bound of contract state size handling.
/// Uses the smallest valid TodoList: {"tasks":[],"version":1}
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 60,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_minimal_state_put_get(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract and create minimal state
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let contract_key = contract.key();
    let minimal_state = create_minimal_state();
    let wrapped_state = WrappedState::from(minimal_state);

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // PUT minimal state
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    let put_result = timeout(Duration::from_secs(30), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            assert_eq!(key, contract_key);
        }
        other => panic!("Unexpected PUT response: {:?}", other),
    }

    // GET minimal state back
    make_get(&mut client, contract_key, true, false).await?;

    let get_result = timeout(Duration::from_secs(10), client.recv()).await;
    match get_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
            state: recv_state,
            ..
        }))) => {
            assert_eq!(recv_state, wrapped_state, "Minimal state should round-trip");
        }
        other => panic!("Unexpected GET response: {:?}", other),
    }

    client
        .send(ClientRequest::Disconnect { cause: None })
        .await?;

    Ok(())
}

/// Test that large states (~1MB) can be stored and retrieved
///
/// Verifies handling of states near the practical size limit without exceeding it.
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 90,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_large_state_put_get(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract and create large state
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let contract_key = contract.key();
    let large_state = create_large_todo_list();
    let wrapped_state = WrappedState::from(large_state.clone());

    tracing::info!("Testing with large state size: {} bytes", large_state.len());

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // PUT large state
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    let put_result = timeout(Duration::from_secs(60), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            assert_eq!(key, contract_key);
            tracing::info!("Large state PUT successful");
        }
        other => panic!("Unexpected PUT response: {:?}", other),
    }

    // GET large state back
    make_get(&mut client, contract_key, true, false).await?;

    let get_result = timeout(Duration::from_secs(30), client.recv()).await;
    match get_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
            state: recv_state,
            ..
        }))) => {
            assert_eq!(recv_state, wrapped_state, "Large state should round-trip");
            tracing::info!(
                "Large state GET successful, verified {} bytes",
                large_state.len()
            );
        }
        other => panic!("Unexpected GET response: {:?}", other),
    }

    client
        .send(ClientRequest::Disconnect { cause: None })
        .await?;

    Ok(())
}

/// Test that empty states work correctly
///
/// Verifies handling of zero-task todo lists (valid but empty contract state).
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 60,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_empty_state_put_get(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract and create empty state
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let contract_key = contract.key();
    let empty_state = freenet::test_utils::create_empty_todo_list();
    let wrapped_state = WrappedState::from(empty_state);

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // PUT empty state
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    let put_result = timeout(Duration::from_secs(30), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            assert_eq!(key, contract_key);
        }
        other => panic!("Unexpected PUT response: {:?}", other),
    }

    // GET empty state back
    make_get(&mut client, contract_key, true, false).await?;

    let get_result = timeout(Duration::from_secs(10), client.recv()).await;
    match get_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
            state: recv_state,
            ..
        }))) => {
            assert_eq!(recv_state, wrapped_state, "Empty state should round-trip");

            // Parse and verify it's truly empty
            let state_str = String::from_utf8_lossy(recv_state.as_ref());
            assert!(
                state_str.contains("\"tasks\":[]"),
                "Empty state should have zero tasks"
            );
        }
        other => panic!("Unexpected GET response: {:?}", other),
    }

    client
        .send(ClientRequest::Disconnect { cause: None })
        .await?;

    Ok(())
}

/// Test that oversized states are properly rejected or handled
///
/// Verifies the system behavior when attempting to store states exceeding
/// practical size limits (10MB+). The system should either:
/// 1. Reject the state with an appropriate error
/// 2. Handle it gracefully (timeout, etc.)
///
/// This test is designed to verify the system doesn't crash or hang
/// when confronted with oversized data.
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 120,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_oversized_state_handling(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract and create oversized state (10MB+)
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let oversized_state = create_oversized_todo_list();
    let wrapped_state = WrappedState::from(oversized_state.clone());

    tracing::info!(
        "Testing oversized state handling: {} bytes ({:.2} MB)",
        oversized_state.len(),
        oversized_state.len() as f64 / (1024.0 * 1024.0)
    );

    // Verify state is actually oversized
    assert!(
        oversized_state.len() > 10_000_000,
        "State should exceed 10MB for this test"
    );

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // Attempt PUT with oversized state
    // This may fail, timeout, or succeed depending on system limits
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    // Wait for response - expect either rejection or timeout
    let put_result = timeout(Duration::from_secs(60), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            tracing::warn!(
                "Oversized state was accepted (key: {}). System may not enforce size limits.",
                key
            );
            // This is acceptable - the system may choose to allow large states
        }
        Ok(Err(err)) => {
            tracing::info!(
                "Oversized state was rejected with error (expected): {:?}",
                err
            );
            // This is the expected behavior - system should reject oversized states
        }
        Err(_timeout) => {
            tracing::info!("Oversized state PUT timed out (acceptable behavior)");
            // Timeout is acceptable - system may be slow to process large states
        }
        Ok(Ok(other)) => {
            tracing::info!("Oversized state got unexpected response: {:?}", other);
            // Any response other than success is acceptable for oversized states
        }
    }

    // Clean disconnect (may fail if connection was dropped)
    let _disconnect = client.send(ClientRequest::Disconnect { cause: None }).await;

    Ok(())
}

/// Test UPDATE operation with no state change (UpdateNoChange scenario)
///
/// This test verifies the UPDATE operation correctly handles the case where
/// the update data results in no state change. This exercises the UpdateNoChange
/// code path which was involved in bug #1734.
///
/// Related to: Bug #1734 - UPDATE operations that result in no state change
/// should still return a proper response, not timeout.
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 90,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_update_no_state_change(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract and create initial state
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let contract_key = contract.key();

    // Create initial state
    let todo_list = TodoList {
        tasks: vec![],
        version: 1,
    };
    let initial_state = serde_json::to_vec(&todo_list)?;
    let wrapped_state = WrappedState::from(initial_state);

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // First PUT the initial state
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    let put_result = timeout(Duration::from_secs(30), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            assert_eq!(key, contract_key);
            tracing::info!("Initial PUT successful");
        }
        other => panic!("Unexpected PUT response: {:?}", other),
    }

    // Now UPDATE with the exact same state (should trigger UpdateNoChange path)
    tracing::info!("Sending UPDATE with identical state to trigger NoChange scenario");
    make_update(&mut client, contract_key, wrapped_state.clone()).await?;

    // Wait for UPDATE response - should NOT timeout even though state is unchanged
    let update_result = timeout(Duration::from_secs(30), client.recv()).await;
    match update_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::UpdateResponse {
            key,
            summary: _,
        }))) => {
            assert_eq!(key, contract_key);
            tracing::info!("UPDATE with no state change completed successfully");
        }
        Ok(Err(err)) => {
            // An error response is acceptable - the contract may reject no-change updates
            tracing::info!("UPDATE returned error (acceptable): {:?}", err);
        }
        Err(_timeout) => {
            // This would be a regression of bug #1734
            panic!("UPDATE operation timed out - possible regression of bug #1734");
        }
        other => panic!("Unexpected UPDATE response: {:?}", other),
    }

    client
        .send(ClientRequest::Disconnect { cause: None })
        .await?;

    Ok(())
}

/// Test state at exact boundary size
///
/// Creates a state close to practical size limits (950KB) to verify
/// edge case handling around the boundary without hitting system limits.
#[freenet_test(
    health_check_readiness = true,
    nodes = ["gateway"],
    timeout_secs = 90,
    startup_wait_secs = 10,
    tokio_flavor = "multi_thread"
)]
async fn test_state_at_boundary_size(ctx: &mut TestContext) -> TestResult {
    let gateway = ctx.gateway()?;

    // Load contract
    const TEST_CONTRACT: &str = "test-contract-integration";
    let contract = load_contract(TEST_CONTRACT, vec![].into())?;
    let contract_key = contract.key();

    // Create a state close to 1MB (practical limit for comfortable operation)
    // We use 950KB to stay safely under 1MB while still testing large state handling
    const TARGET_SIZE: usize = 950 * 1024; // 950KB
    let mut tasks = Vec::new();
    let mut current_size = 0;

    while current_size < TARGET_SIZE {
        let task = Task {
            id: tasks.len() as u64,
            title: format!("Boundary test task {}", tasks.len()),
            description: "X".repeat(100), // Predictable size padding
            completed: false,
            priority: 3,
        };
        // Rough estimate of serialized task size
        current_size += 150;
        tasks.push(task);
    }

    let boundary_state = TodoList { tasks, version: 1 };
    let state_bytes = serde_json::to_vec(&boundary_state)?;
    let wrapped_state = WrappedState::from(state_bytes.clone());

    tracing::info!(
        "Testing boundary state: {} bytes ({:.2} KB)",
        state_bytes.len(),
        state_bytes.len() as f64 / 1024.0
    );

    // Connect to the node
    let (ws_stream, _) = connect_async(&gateway.ws_url()).await?;
    let mut client = WebApi::start(ws_stream);

    // PUT boundary state
    make_put(&mut client, wrapped_state.clone(), contract.clone(), false).await?;

    let put_result = timeout(Duration::from_secs(60), client.recv()).await;
    match put_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::PutResponse { key }))) => {
            assert_eq!(key, contract_key);
            tracing::info!("Boundary state PUT successful");
        }
        other => panic!("Unexpected PUT response for boundary state: {:?}", other),
    }

    // GET boundary state back to verify round-trip
    make_get(&mut client, contract_key, true, false).await?;

    let get_result = timeout(Duration::from_secs(30), client.recv()).await;
    match get_result {
        Ok(Ok(HostResponse::ContractResponse(ContractResponse::GetResponse {
            state: recv_state,
            ..
        }))) => {
            assert_eq!(
                recv_state, wrapped_state,
                "Boundary state should round-trip"
            );
            tracing::info!(
                "Boundary state GET successful, verified {} bytes",
                state_bytes.len()
            );
        }
        other => panic!("Unexpected GET response for boundary state: {:?}", other),
    }

    client
        .send(ClientRequest::Disconnect { cause: None })
        .await?;

    Ok(())
}