-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_start.md
More file actions
581 lines (464 loc) Β· 15.9 KB
/
quick_start.md
File metadata and controls
581 lines (464 loc) Β· 15.9 KB
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
#!/bin/bash
# Mycelia Network - Quick Start Script
# This gets you running in 5 minutes!
set -e
# Colors for output
RED=β\033[0;31mβ
GREEN=β\033[0;32mβ
BLUE=β\033[0;34mβ
YELLOW=β\033[1;33mβ
NC=β\033[0mβ # No Color
echo -e β${BLUE}π Mycelia Network Quick Start${NC}β
echo -e β${YELLOW}Building the future of decentralized social networking!${NC}β
echo ββ
# Check prerequisites
echo -e β${BLUE}π Checking prerequisitesβ¦${NC}β
if ! command -v cargo &> /dev/null; then
echo -e β${RED}β Rust/Cargo not found. Please install Rust first:${NC}β
echo βcurl βproto β=httpsβ βtlsv1.2 -sSf https://sh.rustup.rs | shβ
exit 1
fi
if ! command -v node &> /dev/null; then
echo -e β${YELLOW}β οΈ Node.js not found. Desktop app wonβt work without it.${NC}β
else
echo -e β${GREEN}β
Node.js found${NC}β
fi
echo -e β${GREEN}β
Rust/Cargo found${NC}β
# Create workspace
WORKSPACE=βunivrs-mycelia-quickstartβ
echo -e β${BLUE}π Creating workspace: $WORKSPACE${NC}β
if [ -d β$WORKSPACEβ ]; then
echo -e β${YELLOW}β οΈ Directory exists. Remove it? (y/n)${NC}β
read -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
rm -rf β$WORKSPACEβ
else
echo βExitingβ¦β
exit 1
fi
fi
mkdir β$WORKSPACEβ && cd β$WORKSPACEβ
# Initialize Cargo workspace
echo -e β${BLUE}π§ Setting up Cargo workspaceβ¦${NC}β
cat > Cargo.toml << βEOFβ
[workspace]
members = [βmycelia-simpleβ]
resolver = β2β
[workspace.dependencies]
libp2p = β0.53β
tokio = { version = β1.0β, features = [βfullβ] }
serde = { version = β1.0β, features = [βderiveβ] }
bincode = β1.3β
blake3 = β1.5β
uuid = { version = β1.0β, features = [βv4β] }
chrono = { version = β0.4β, features = [βserdeβ] }
env_logger = β0.10β
rand = β0.8β
hex = β0.4β
ed25519-dalek = β2.0β
clap = { version = β4.0β, features = [βderiveβ] }
EOF
# Create simple node implementation
echo -e β${BLUE}π Creating simple Mycelia nodeβ¦${NC}β
cargo new βbin mycelia-simple
cd mycelia-simple
# Setup dependencies
cat > Cargo.toml << βEOFβ
[package]
name = βmycelia-simpleβ
version = β0.1.0β
edition = β2021β
[dependencies]
libp2p = { workspace = true, features = [βtcpβ, βnoiseβ, βyamuxβ, βgossipsubβ, βmdnsβ] }
tokio = { workspace = true }
serde = { workspace = true }
bincode = { workspace = true }
blake3 = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
env_logger = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
ed25519-dalek = { workspace = true }
clap = { workspace = true }
EOF
# Create the main implementation
cat > src/main.rs << βEOFβ
//! Simple Mycelia Network Node
//! A minimal implementation to get started quickly
use libp2p::{
gossipsub::{self, MessageAuthenticity, ValidationMode, Event as GossipEvent},
mdns::{Event as MdnsEvent},
noise, tcp, yamux,
swarm::{NetworkBehaviour, SwarmEvent, SwarmBuilder},
PeerId, Multiaddr,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io;
use tokio::io::AsyncBufReadExt;
use clap::Parser;
#[derive(Parser)]
#[command(name = βmycelia-simpleβ)]
#[command(about = βA simple Mycelia Network nodeβ)]
struct Args {
#[arg(short, long, default_value = β0β)]
port: u16,
```
#[arg(short, long)]
peer: Option<Multiaddr>,
#[arg(short, long, default_value = "Anonymous")]
name: String,
```
}
#[derive(NetworkBehaviour)]
struct MyceliaBehaviour {
gossipsub: gossipsub::Behaviour,
mdns: libp2p::mdns::tokio::Behaviour,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SimplePost {
id: String,
author: String,
content: String,
timestamp: chrono::DateTime<chrono::Utc>,
}
impl SimplePost {
fn new(author: String, content: String) -> Self {
Self {
id: uuid::Uuid::new_v4().to_string(),
author,
content,
timestamp: chrono::Utc::now(),
}
}
}
struct MyceliaNode {
swarm: libp2p::Swarm<MyceliaBehaviour>,
posts: HashMap<String, SimplePost>,
node_name: String,
}
impl MyceliaNode {
async fn new(node_name: String) -> Result<Self, Box<dyn std::error::Error>> {
let local_key = libp2p::identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
```
println!("π Local peer id: {local_peer_id}");
println!("π€ Node name: {node_name}");
let transport = tcp::tokio::Transport::default()
.upgrade(libp2p::core::upgrade::Version::V1)
.authenticate(noise::Config::new(&local_key)?)
.multiplex(yamux::Config::default())
.boxed();
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(std::time::Duration::from_secs(10))
.validation_mode(ValidationMode::Strict)
.build()?;
let gossipsub = gossipsub::Behaviour::new(
MessageAuthenticity::Signed(local_key),
gossipsub_config,
)?;
let mdns = libp2p::mdns::tokio::Behaviour::new(
libp2p::mdns::Config::default(),
local_peer_id,
)?;
let behaviour = MyceliaBehaviour { gossipsub, mdns };
let swarm = SwarmBuilder::with_tokio_executor(transport, behaviour, local_peer_id).build();
Ok(Self {
swarm,
posts: HashMap::new(),
node_name,
})
}
async fn start_listening(&mut self, port: u16) -> Result<(), Box<dyn std::error::Error>> {
let addr = if port == 0 {
"/ip4/0.0.0.0/tcp/0".parse()?
} else {
format!("/ip4/0.0.0.0/tcp/{}", port).parse()?
};
self.swarm.listen_on(addr)?;
// Subscribe to the main topic
let topic = gossipsub::IdentTopic::new("mycelia-chat");
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
Ok(())
}
async fn connect_to_peer(&mut self, addr: Multiaddr) -> Result<(), Box<dyn std::error::Error>> {
self.swarm.dial(addr)?;
Ok(())
}
fn publish_post(&mut self, content: String) -> Result<(), Box<dyn std::error::Error>> {
let post = SimplePost::new(self.node_name.clone(), content);
let post_id = post.id.clone();
// Serialize and publish
let message = bincode::serialize(&post)?;
let topic = gossipsub::IdentTopic::new("mycelia-chat");
self.swarm.behaviour_mut().gossipsub.publish(topic, message)?;
// Store locally
self.posts.insert(post_id.clone(), post);
println!("π€ Published post: {}", post_id);
Ok(())
}
fn handle_received_post(&mut self, post: SimplePost) {
println!("π¨ Received post from {}: {}", post.author, post.content);
self.posts.insert(post.id.clone(), post);
}
fn list_posts(&self) {
if self.posts.is_empty() {
println!("π No posts yet. Type 'post <message>' to create one!");
return;
}
println!("π Recent posts:");
let mut posts: Vec<_> = self.posts.values().collect();
posts.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
for (i, post) in posts.iter().take(10).enumerate() {
let time = post.timestamp.format("%H:%M:%S");
println!(" {}. [{}] {}: {}", i + 1, time, post.author, post.content);
}
}
async fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
let mut stdin = tokio::io::BufReader::new(tokio::io::stdin()).lines();
println!("π Mycelia node is running!");
println!("π¬ Commands:");
println!(" post <message> - Publish a post");
println!(" list - Show recent posts");
println!(" peers - Show connected peers");
println!(" quit - Exit");
println!();
loop {
tokio::select! {
line = stdin.next_line() => {
if let Ok(Some(line)) = line {
self.handle_input(line.trim()).await?;
}
}
event = self.swarm.select_next_some() => {
self.handle_swarm_event(event).await?;
}
}
}
}
async fn handle_input(&mut self, input: &str) -> Result<(), Box<dyn std::error::Error>> {
let parts: Vec<&str> = input.splitn(2, ' ').collect();
match parts[0] {
"post" => {
if parts.len() > 1 {
self.publish_post(parts[1].to_string())?;
} else {
println!("Usage: post <message>");
}
}
"list" => {
self.list_posts();
}
"peers" => {
let peer_count = self.swarm.connected_peers().count();
println!("π€ Connected peers: {}", peer_count);
for peer in self.swarm.connected_peers() {
println!(" - {}", peer);
}
}
"quit" | "exit" => {
println!("π Goodbye!");
std::process::exit(0);
}
"help" => {
println!("π¬ Available commands:");
println!(" post <message> - Publish a post");
println!(" list - Show recent posts");
println!(" peers - Show connected peers");
println!(" quit - Exit");
}
"" => {
// Empty input, do nothing
}
_ => {
println!("β Unknown command: {}. Type 'help' for available commands.", parts[0]);
}
}
Ok(())
}
async fn handle_swarm_event(
&mut self,
event: SwarmEvent<MyceliaBehaviourEvent>,
) -> Result<(), Box<dyn std::error::Error>> {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
println!("π‘ Listening on {address}");
}
SwarmEvent::Behaviour(MyceliaBehaviourEvent::Gossipsub(GossipEvent::Message {
message,
..
})) => {
if let Ok(post) = bincode::deserialize::<SimplePost>(&message.data) {
// Don't show our own posts again
if post.author != self.node_name {
self.handle_received_post(post);
}
}
}
SwarmEvent::Behaviour(MyceliaBehaviourEvent::Mdns(MdnsEvent::Discovered(peers))) => {
for (peer_id, _) in peers {
println!("π€ Discovered peer: {peer_id}");
self.swarm.behaviour_mut().gossipsub.add_explicit_peer(&peer_id);
}
}
SwarmEvent::Behaviour(MyceliaBehaviourEvent::Mdns(MdnsEvent::Expired(peers))) => {
for (peer_id, _) in peers {
println!("π Peer expired: {peer_id}");
self.swarm.behaviour_mut().gossipsub.remove_explicit_peer(&peer_id);
}
}
SwarmEvent::ConnectionEstablished { peer_id, .. } => {
println!("π Connected to peer: {peer_id}");
}
SwarmEvent::ConnectionClosed { peer_id, .. } => {
println!("β Disconnected from peer: {peer_id}");
}
_ => {}
}
Ok(())
}
```
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
```
let args = Args::parse();
let mut node = MyceliaNode::new(args.name).await?;
node.start_listening(args.port).await?;
if let Some(peer_addr) = args.peer {
println!("π Connecting to peer: {}", peer_addr);
node.connect_to_peer(peer_addr).await?;
}
node.run().await
```
}
EOF
# Build the project
echo -e β${BLUE}π¨ Building the projectβ¦${NC}β
cargo build βrelease
# Create a demo script
echo -e β${BLUE}π Creating demo scriptβ¦${NC}β
cd ..
cat > demo.sh << βEOFβ
#!/bin/bash
# Mycelia Network Demo
echo βπ Mycelia Network Demoβ
echo βThis will start 3 nodes that can talk to each otherβ
echo ββ
# Start first node (bootstrap)
echo βStarting bootstrap node on port 4001β¦β
RUST_LOG=info cargo run βbin mycelia-simple β βport 4001 βname βBootstrapβ &
BOOTSTRAP_PID=$!
sleep 2
# Start second node
echo βStarting second node on port 4002β¦β
RUST_LOG=info cargo run βbin mycelia-simple β βport 4002 βname βAliceβ βpeer /ip4/127.0.0.1/tcp/4001 &
ALICE_PID=$!
sleep 2
# Start third node
echo βStarting third node on port 4003β¦β
RUST_LOG=info cargo run βbin mycelia-simple β βport 4003 βname βBobβ βpeer /ip4/127.0.0.1/tcp/4001 &
BOB_PID=$!
echo ββ
echo βπ Network started!β
echo βπ± Open 3 terminals and connect to each node:β
echo β Node 1 (Bootstrap): telnet localhost 4001β
echo β Node 2 (Alice): telnet localhost 4002β
echo β Node 3 (Bob): telnet localhost 4003β
echo ββ
echo βπ¬ Try posting messages and see them propagate!β
echo β Commands: post <message>, list, peers, quitβ
echo ββ
echo βPress Ctrl+C to stop all nodesβ¦β
# Handle cleanup
trap βecho ββ; echo βStopping nodesβ¦β; kill $BOOTSTRAP_PID $ALICE_PID $BOB_PID 2>/dev/null; exitβ INT
wait
EOF
chmod +x demo.sh
# Create README
cat > README.md << βEOFβ
# π Mycelia Network - Quick Start
Youβve successfully set up a minimal Mycelia Network node!
## What You Have
- A working P2P network node built with libp2p
- Peer discovery using mDNS (finds other nodes automatically)
- Content sharing via gossipsub protocol
- Simple command-line interface
## Running Your First Network
### Single Node
```bash
cargo run --bin mycelia-simple -- --name "YourName"
```
### Multi-Node Network
```bash
# Terminal 1 - Bootstrap node
cargo run --bin mycelia-simple -- --port 4001 --name "Bootstrap"
# Terminal 2 - Connect to bootstrap
cargo run --bin mycelia-simple -- --port 4002 --name "Alice" --peer /ip4/127.0.0.1/tcp/4001
# Terminal 3 - Another peer
cargo run --bin mycelia-simple -- --port 4003 --name "Bob" --peer /ip4/127.0.0.1/tcp/4001
```
### Or Use the Demo Script
```bash
./demo.sh
```
## Commands
Once your node is running, try these commands:
- `post Hello, Mycelia Network!` - Publish a message
- `list` - Show recent posts
- `peers` - Show connected peers
- `help` - Show all commands
- `quit` - Exit
## Whatβs Next?
This is just the beginning! From here you can:
1. **Add Math Integration**: Connect your dynamic-math platform for social algorithms
1. **Create Communities**: Build governance and moderation features
1. **Add Desktop UI**: Create the Tauri app for a better user experience
1. **Deploy to Cloud**: Set up bootstrap nodes for a real network
1. **Build Mobile Apps**: Create React Native or Flutter apps
## Features to Add
- User reputation systems
- Community governance
- Content moderation
- File sharing
- End-to-end encryption
- Mobile apps
- Web interface
## Architecture
```
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β Node A βββββΊβ Node B βββββΊβ Node C β
β (Bootstrap)β β (Alice) β β (Bob) β
β β β β β β
β Port: 4001 β β Port: 4002 β β Port: 4003 β
βββββββββββββββ βββββββββββββββ βββββββββββββββ
β² β² β²
β β β
βββββββββββββββββββββΌββββββββββββββββββββ
β
π‘ P2P Network
(libp2p + gossipsub)
```
Happy building! π
EOF
echo ββ
echo -e β${GREEN}β
Mycelia Network Quick Start is ready!${NC}β
echo ββ
echo -e β${BLUE}π To get started:${NC}β
echo -e β 1. cd $WORKSPACEβ
echo -e β 2. cargo run βbin mycelia-simple β βname "YourName"β
echo -e β 3. Type βpost Hello, Mycelia!β to publish your first messageβ
echo ββ
echo -e β${BLUE}π For a multi-node demo:${NC}β
echo -e β 1. cd $WORKSPACEβ
echo -e β 2. ./demo.shβ
echo ββ
echo -e β${YELLOW}π Read README.md for more details${NC}β
echo ββ
echo -e β${GREEN}π Welcome to the Mycelia Network!${NC}β
echo -e β${GREEN} βOf the people, by the people, and for the people!β${NC}β
EOF
chmod +x quick_start.sh