chaincraft 0.3.2

A high-performance Rust-based platform for blockchain education and prototyping
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
use anyhow::Result;
use chaincraft::{
    network::PeerId,
    shared::{MessageType, SharedMessage},
    storage::MemoryStorage,
    ChaincraftNode,
};
use serde_json::json;
use std::f64::consts::PI;
use std::sync::Arc;
use tokio::time::{sleep, Duration};

/// Helper function to connect nodes in a full mesh
async fn connect_nodes(nodes: &mut [ChaincraftNode]) -> Result<()> {
    for i in 0..nodes.len() {
        for j in 0..nodes.len() {
            if i != j {
                let peer_addr = format!("{}:{}", nodes[j].host(), nodes[j].port());
                nodes[i].connect_to_peer(&peer_addr).await?;
            }
        }
    }
    Ok(())
}

/// Helper function to wait for message propagation (simplified for testing)
#[allow(dead_code)]
async fn wait_for_message_propagation(
    nodes: &[ChaincraftNode],
    expected_count: usize,
    timeout_secs: u64,
) -> bool {
    let start = std::time::Instant::now();
    let timeout = Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        let counts: Vec<usize> = nodes.iter().map(|node| node.db_size()).collect();
        if counts.iter().all(|&count| count == expected_count) {
            return true;
        }
        sleep(Duration::from_millis(100)).await;
    }
    false
}

async fn create_test_node() -> ChaincraftNode {
    let id = PeerId::new();
    let storage = Arc::new(MemoryStorage::new());
    let mut node = ChaincraftNode::new(id, storage);
    node.set_port(0); // Use ephemeral port
    node.start().await.expect("Failed to start node");
    node
}

#[tokio::test]
async fn test_text_message_creation() {
    let mut node = create_test_node().await;

    let message_id = node
        .create_shared_message_with_data(json!("Hello, World!"))
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_json_object_message() {
    let mut node = create_test_node().await;

    let data = json!({
        "type": "user_action",
        "action": "login",
        "user_id": 12345,
        "timestamp": "2024-01-01T00:00:00Z"
    });

    let message_id = node
        .create_shared_message_with_data(data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_array_message() {
    let mut node = create_test_node().await;

    let data = json!([1, 2, 3, 4, 5]);
    let message_id = node
        .create_shared_message_with_data(data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_nested_object_message() {
    let mut node = create_test_node().await;

    let data = json!({
        "user": {
            "id": 123,
            "profile": {
                "name": "Alice",
                "preferences": {
                    "theme": "dark",
                    "notifications": true
                }
            }
        },
        "metadata": {
            "version": "1.0",
            "created_at": "2024-01-01T00:00:00Z"
        }
    });

    let message_id = node
        .create_shared_message_with_data(data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_large_message() {
    let mut node = create_test_node().await;

    // Create a large message with repeated data
    let large_data = json!({
        "type": "bulk_data",
        "items": (0..100).map(|i| json!({
            "id": i,
            "value": format!("item_{}", i),
            "metadata": {
                "created": "2024-01-01T00:00:00Z",
                "tags": ["tag1", "tag2", "tag3"]
            }
        })).collect::<Vec<_>>()
    });

    let message_id = node
        .create_shared_message_with_data(large_data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_message_with_special_characters() {
    let mut node = create_test_node().await;

    let data = json!({
        "text": "Hello 🌍! Special chars: àáâãäåæçèéêë",
        "unicode": "🚀🎉💻🔥⭐",
        "symbols": "!@#$%^&*()_+-=[]{}|;':\",./<>?",
        "newlines": "Line 1\nLine 2\r\nLine 3\tTabbed"
    });

    let message_id = node
        .create_shared_message_with_data(data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_message_serialization_roundtrip() -> Result<()> {
    let mut node = create_test_node().await;
    let data = json!({
        "test": "data",
        "number": 42,
        "nested": { "field": "value" }
    });
    let message_id = node.create_shared_message_with_data(data.clone()).await?;
    let mut message_json = None;
    for _ in 0..10 {
        if let Some(obj) = node
            .get_object(&message_id)
            .await
            .ok()
            .filter(|s| !s.is_empty())
        {
            message_json = Some(obj);
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
    }
    let message_json = message_json.expect("Message object not found");
    let value: serde_json::Value = serde_json::from_str(&message_json)?;
    let parsed_data = &value["data"];
    assert_eq!(parsed_data, &data);
    node.close().await?;
    Ok(())
}

#[tokio::test]
async fn test_message_id_uniqueness() {
    let mut node = create_test_node().await;

    let mut message_ids = std::collections::HashSet::new();

    // Create multiple messages and ensure IDs are unique
    for i in 0..10 {
        let message_id = node
            .create_shared_message_with_data(json!(i))
            .await
            .unwrap();
        assert!(message_ids.insert(message_id), "Message ID should be unique");
    }

    assert_eq!(message_ids.len(), 10);

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_message_ordering() -> Result<()> {
    let mut node = create_test_node().await;
    let mut messages = Vec::new();
    for i in 0..5 {
        let data = json!({ "index": i, "data": format!("message_{}", i) });
        let msg_id = node.create_shared_message_with_data(data).await?;
        let mut msg_json = None;
        for _ in 0..10 {
            if let Some(obj) = node
                .get_object(&msg_id)
                .await
                .ok()
                .filter(|s| !s.is_empty())
            {
                msg_json = Some(obj);
                break;
            }
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
        let msg_json = msg_json.expect("Message object not found");
        let value: serde_json::Value = serde_json::from_str(&msg_json)?;
        let timestamp = value["timestamp"].as_i64().unwrap_or(0);
        messages.push((msg_id, timestamp));
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
    }
    for i in 1..messages.len() {
        let prev_ts = messages[i - 1].1;
        let curr_ts = messages[i].1;
        assert!(
            curr_ts >= prev_ts,
            "Message timestamps should be monotonically increasing or equal"
        );
    }
    node.close().await?;
    Ok(())
}

#[tokio::test]
async fn test_empty_message_data() {
    let mut node = create_test_node().await;

    let empty_data = json!({});
    let message_id = node
        .create_shared_message_with_data(empty_data.clone())
        .await
        .unwrap();
    assert!(!message_id.is_empty());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_simple_string_message() -> Result<()> {
    let mut nodes: Vec<ChaincraftNode> = vec![
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
    ];

    for node in &mut nodes {
        node.start().await?;
    }

    connect_nodes(&mut nodes).await?;

    // Create a simple string message
    let _hash = nodes[0]
        .create_shared_message("Hello, world!".to_string())
        .await?;

    // For now, just verify the message was created
    // Real propagation would require gossip protocol implementation
    assert_eq!(nodes[0].db_size(), 1);

    // Cleanup
    for mut node in nodes {
        node.close().await?;
    }

    Ok(())
}

#[tokio::test]
async fn test_simple_integer_message() -> Result<()> {
    let mut nodes = vec![
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
    ];

    for node in &mut nodes {
        node.start().await?;
    }

    connect_nodes(&mut nodes).await?;

    // Create a message with integer data
    let _hash = nodes[0].create_shared_message("42".to_string()).await?;

    // Verify the message was created
    assert_eq!(nodes[0].db_size(), 1);

    // Cleanup
    for mut node in nodes {
        node.close().await?;
    }

    Ok(())
}

#[tokio::test]
async fn test_json_message() -> Result<()> {
    let mut nodes = vec![
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
    ];

    for node in &mut nodes {
        node.start().await?;
    }

    connect_nodes(&mut nodes).await?;

    // Create a JSON-structured message similar to the Python test
    let user_data = json!({
        "message_type": "User",
        "user_id": 1,
        "username": "alice",
        "email": "alice@example.com",
        "bio": "Hello, I'm Alice!"
    });

    let _hash = nodes[0]
        .create_shared_message(user_data.to_string())
        .await?;

    // Verify the message was created
    assert_eq!(nodes[0].db_size(), 1);

    // Cleanup
    for mut node in nodes {
        node.close().await?;
    }

    Ok(())
}

#[tokio::test]
async fn test_complex_nested_message() -> Result<()> {
    let mut nodes = vec![
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
        ChaincraftNode::builder()
            .port(0)
            .with_persistent_storage(false)
            .persist_peers(false)
            .build()?,
    ];

    for node in &mut nodes {
        node.start().await?;
    }

    connect_nodes(&mut nodes).await?;

    // Create a complex nested message similar to the transaction/block example
    let transaction1 = json!({
        "message_type": "Transaction",
        "sender": "Alice",
        "recipient": "Bob",
        "amount": 10.0,
        "signature": "a1b2c3d4e5f6g7h8i9j0"
    });

    let transaction2 = json!({
        "message_type": "Transaction",
        "sender": "Bob",
        "recipient": "Charlie",
        "amount": 5.0,
        "signature": "k1l2m3n4o5p6q7r8s9t0"
    });

    let block = json!({
        "message_type": "Block",
        "block_number": 1,
        "transactions": [transaction1, transaction2],
        "previous_hash": "0000000000000000000000000000000000000000000000000000000000000000",
        "timestamp": chrono::Utc::now().timestamp(),
        "nonce": 1234
    });

    let _hash = nodes[0].create_shared_message(block.to_string()).await?;

    // Verify the message was created
    assert_eq!(nodes[0].db_size(), 1);

    // Cleanup
    for mut node in nodes {
        node.close().await?;
    }

    Ok(())
}

#[tokio::test]
async fn test_node_state_access() {
    let mut node = create_test_node().await;

    // Create some messages
    for i in 0..3 {
        node.create_shared_message_with_data(json!({"test": i}))
            .await
            .unwrap();
    }

    // Test node state access
    let state = node.get_state().await.unwrap();
    assert!(state.is_object());
    assert!(state.get("node_id").is_some());
    assert!(state.get("running").is_some());

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_null_and_boolean_messages() {
    let mut node = create_test_node().await;

    // Test null value
    let null_id = node
        .create_shared_message_with_data(json!(null))
        .await
        .unwrap();
    assert!(!null_id.is_empty());

    // Test boolean values
    let true_id = node
        .create_shared_message_with_data(json!(true))
        .await
        .unwrap();
    assert!(!true_id.is_empty());

    let false_id = node
        .create_shared_message_with_data(json!(false))
        .await
        .unwrap();
    assert!(!false_id.is_empty());

    // All IDs should be different
    assert_ne!(null_id, true_id);
    assert_ne!(true_id, false_id);
    assert_ne!(null_id, false_id);

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_numeric_messages() {
    let mut node = create_test_node().await;

    // Test various numeric types
    let int_id = node
        .create_shared_message_with_data(json!(42))
        .await
        .unwrap();
    let negative_id = node
        .create_shared_message_with_data(json!(-123))
        .await
        .unwrap();
    let float_id = node
        .create_shared_message_with_data(json!(PI))
        .await
        .unwrap();
    let zero_id = node
        .create_shared_message_with_data(json!(0))
        .await
        .unwrap();

    // All should create valid message IDs
    assert!(!int_id.is_empty());
    assert!(!negative_id.is_empty());
    assert!(!float_id.is_empty());
    assert!(!zero_id.is_empty());

    // All IDs should be unique
    let ids = [int_id, negative_id, float_id, zero_id];
    let unique_ids: std::collections::HashSet<_> = ids.iter().collect();
    assert_eq!(unique_ids.len(), 4);

    node.close().await.unwrap();
}

#[tokio::test]
async fn test_message_timestamp_ordering() -> Result<()> {
    let mut node = create_test_node().await;

    // Create messages with different timestamps
    let mut messages = Vec::new();
    for i in 0..5 {
        let data = json!({ "index": i });
        let message = SharedMessage::new(MessageType::Custom("test".to_string()), data);
        let timestamp = message.timestamp;
        messages.push((message, timestamp));
        sleep(Duration::from_millis(10)).await;
    }

    // Verify timestamps are in ascending order
    for i in 1..messages.len() {
        assert!(messages[i].1 >= messages[i - 1].1, "Messages should be ordered by timestamp");
    }

    node.close().await?;
    Ok(())
}

#[tokio::test]
async fn test_shared_object_id_variants() -> Result<(), Box<dyn std::error::Error>> {
    let mut node1 = create_test_node().await;
    let mut node2 = create_test_node().await;

    // Test numeric message types
    let int_id = node1
        .create_shared_message_with_data(json!(42))
        .await
        .unwrap();

    let negative_id = node1
        .create_shared_message_with_data(json!(-123))
        .await
        .unwrap();

    // Use PI constant instead of approximation
    let float_id = node1
        .create_shared_message_with_data(json!(PI))
        .await
        .unwrap();

    let zero_id = node1
        .create_shared_message_with_data(json!(0))
        .await
        .unwrap();

    // All IDs should be unique
    let ids = [&int_id, &negative_id, &float_id, &zero_id];
    let unique_ids: std::collections::HashSet<_> = ids.iter().collect();
    assert_eq!(unique_ids.len(), 4);

    // Clean up nodes
    node1.close().await?;
    node2.close().await?;

    Ok(())
}