Migrate to YAW/2 protocol: WebRTC transport, anchor signaling, nacl/box crypto
Replace the original raw-TCP peer connections and Blowfish/RSA-era design with the YAW/2 protocol stack: Transport - internal/mesh/peer.go: raw TCP + manual ECDH replaced with pion/webrtc DataChannels (ICE, DTLS, SCTP). Peers negotiate via sealed offer/answer/ candidate exchange rather than direct dialling. - internal/nat: deleted — ICE subsumes everything this package was going to do. Signaling - cmd/anchor: new WebSocket signaling server (replaces cmd/relay). Verifies Ed25519 challenge/join signatures, routes opaque nacl/box blobs, broadcasts peer-join/peer-leave events. Never sees plaintext signaling content. - internal/anchor: new anchor client. Manages PeerConnection lifecycle, decides offerer by peer-id comparison, seals/opens signaling payloads with nacl/box, implements mesh.Anchor. Crypto (internal/crypto) - PeerID encoding: base64url → lowercase hex (64 chars, YAW/2 §2). - Sign/Verify: hex signatures throughout. - Added CurvePublicKey/CurvePrivateKey: X25519 keys derived from Ed25519 identity via Montgomery conversion (filippo.io/edwards25519), matching libsodium's crypto_sign_ed25519_*_to_curve25519. - Added SignalingBox/SignalingOpen: nacl/box (XSalsa20-Poly1305) seal/open for signaling payloads. Wire types (internal/proto) - ChatMessage gains Mid (random 16-byte hex) for mesh deduplication (§8). - FileChunk removed from PeerMessage — chunks go on a separate binary DataChannel labelled "f:<xid>"; FileDone added. - New types: SignalingPayload, AnchorMessage, HelloMessage, HelloBindString. - PeerID.Short() now returns first 16 hex chars grouped in 4s. - IPC: CmdConnect removed; CmdJoinNetwork/CmdLeaveNetwork added; EvtSessionReady added (fires when DataChannel opens and hello is received). IPC (internal/ipc) - join_network/leave_network replace connect (direct TCP dial). - Network joins are context-scoped: leave_network or client disconnect cancels the anchor connection cleanly. README updated to reflect new project layout, getting-started commands, IPC protocol, and roadmap state. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,9 @@ package ipc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -16,8 +19,12 @@ import (
|
||||
"github.com/waste-go/internal/proto"
|
||||
)
|
||||
|
||||
// JoinFunc is called when the UI issues a join_network command.
|
||||
// It should connect to the anchor and block until done or ctx is cancelled.
|
||||
type JoinFunc func(ctx context.Context, networkName string)
|
||||
|
||||
// Run starts the IPC listener. Blocks until the listener fails.
|
||||
func Run(m *mesh.Mesh, port int) error {
|
||||
func Run(m *mesh.Mesh, port int, join JoinFunc) error {
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
ln, err := net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
@@ -31,21 +38,18 @@ func Run(m *mesh.Mesh, port int) error {
|
||||
return fmt.Errorf("ipc accept: %w", err)
|
||||
}
|
||||
log.Printf("ipc: UI client connected from %s", conn.RemoteAddr())
|
||||
go handleClient(conn, m)
|
||||
go handleClient(conn, m, join)
|
||||
}
|
||||
}
|
||||
|
||||
func handleClient(conn net.Conn, m *mesh.Mesh) {
|
||||
func handleClient(conn net.Conn, m *mesh.Mesh, join JoinFunc) {
|
||||
defer conn.Close()
|
||||
|
||||
// Subscribe to mesh events before anything else so we miss nothing.
|
||||
events := m.Subscribe()
|
||||
defer m.Unsubscribe(events)
|
||||
|
||||
// Channel to serialize writes from two goroutines (event pusher + reply sender).
|
||||
writeCh := make(chan []byte, 128)
|
||||
|
||||
// Writer goroutine — single goroutine owns the connection write side.
|
||||
go func() {
|
||||
w := bufio.NewWriter(conn)
|
||||
for line := range writeCh {
|
||||
@@ -57,7 +61,6 @@ func handleClient(conn net.Conn, m *mesh.Mesh) {
|
||||
}
|
||||
}()
|
||||
|
||||
// Event pusher goroutine — forwards mesh events to the UI.
|
||||
go func() {
|
||||
for evt := range events {
|
||||
line, err := json.Marshal(evt)
|
||||
@@ -71,7 +74,6 @@ func handleClient(conn net.Conn, m *mesh.Mesh) {
|
||||
}
|
||||
}()
|
||||
|
||||
// Send an initial state snapshot so the UI has something to render.
|
||||
send(writeCh, proto.IpcMessage{
|
||||
Type: proto.EvtStateSnapshot,
|
||||
LocalPeer: ptr(m.Identity.PeerInfo()),
|
||||
@@ -79,7 +81,11 @@ func handleClient(conn net.Conn, m *mesh.Mesh) {
|
||||
Rooms: []string{"general"},
|
||||
})
|
||||
|
||||
// Command reader loop.
|
||||
// Track an active network join so we can cancel it on leave_network.
|
||||
var (
|
||||
networkCancel context.CancelFunc
|
||||
)
|
||||
|
||||
scanner := bufio.NewScanner(conn)
|
||||
for scanner.Scan() {
|
||||
var cmd proto.IpcMessage
|
||||
@@ -87,68 +93,67 @@ func handleClient(conn net.Conn, m *mesh.Mesh) {
|
||||
log.Printf("ipc: bad command: %v", err)
|
||||
continue
|
||||
}
|
||||
handleCommand(cmd, m, writeCh)
|
||||
|
||||
switch cmd.Type {
|
||||
|
||||
case proto.CmdSendMessage:
|
||||
msg := &proto.ChatMessage{
|
||||
Mid: randomHex(16),
|
||||
ID: uuid.NewString(),
|
||||
From: m.Identity.PeerID(),
|
||||
To: cmd.To,
|
||||
Room: cmd.Room,
|
||||
Body: cmd.Body,
|
||||
SentAt: time.Now(),
|
||||
}
|
||||
payload, err := json.Marshal(proto.PeerMessage{Type: proto.MsgChat, Chat: msg})
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
m.Broadcast(payload)
|
||||
m.Emit(proto.IpcMessage{Type: proto.EvtMessageReceived, Message: msg})
|
||||
|
||||
case proto.CmdJoinNetwork:
|
||||
if cmd.NetworkName == "" {
|
||||
send(writeCh, errMsg("join_network: network_name is required"))
|
||||
continue
|
||||
}
|
||||
if networkCancel != nil {
|
||||
networkCancel() // leave any previous network
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
networkCancel = cancel
|
||||
go join(ctx, cmd.NetworkName)
|
||||
|
||||
case proto.CmdLeaveNetwork:
|
||||
if networkCancel != nil {
|
||||
networkCancel()
|
||||
networkCancel = nil
|
||||
}
|
||||
|
||||
case proto.CmdGetState:
|
||||
send(writeCh, proto.IpcMessage{
|
||||
Type: proto.EvtStateSnapshot,
|
||||
LocalPeer: ptr(m.Identity.PeerInfo()),
|
||||
ConnectedPeers: m.ConnectedPeers(),
|
||||
Rooms: []string{"general"},
|
||||
})
|
||||
|
||||
case proto.CmdSendFile:
|
||||
send(writeCh, errMsg("file transfer not yet implemented"))
|
||||
|
||||
default:
|
||||
send(writeCh, errMsg(fmt.Sprintf("unknown command: %s", cmd.Type)))
|
||||
}
|
||||
}
|
||||
|
||||
if networkCancel != nil {
|
||||
networkCancel()
|
||||
}
|
||||
close(writeCh)
|
||||
log.Printf("ipc: UI client disconnected")
|
||||
}
|
||||
|
||||
func handleCommand(cmd proto.IpcMessage, m *mesh.Mesh, writeCh chan<- []byte) {
|
||||
switch cmd.Type {
|
||||
|
||||
case proto.CmdSendMessage:
|
||||
msg := &proto.ChatMessage{
|
||||
ID: uuid.NewString(),
|
||||
From: m.Identity.PeerID(),
|
||||
To: cmd.To,
|
||||
Room: cmd.Room,
|
||||
Body: cmd.Body,
|
||||
SentAt: time.Now(),
|
||||
}
|
||||
payload, err := json.Marshal(proto.PeerMessage{
|
||||
Type: proto.MsgChat,
|
||||
Chat: msg,
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.Broadcast(payload)
|
||||
// Echo locally so the sender sees their own message.
|
||||
m.Emit(proto.IpcMessage{Type: proto.EvtMessageReceived, Message: msg})
|
||||
|
||||
case proto.CmdConnect:
|
||||
if cmd.Addr == "" {
|
||||
send(writeCh, errMsg("connect: addr is required"))
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
log.Printf("ipc: connecting to peer at %s", cmd.Addr)
|
||||
conn, err := net.DialTimeout("tcp", cmd.Addr, 10*time.Second)
|
||||
if err != nil {
|
||||
log.Printf("ipc: dial %s failed: %v", cmd.Addr, err)
|
||||
m.Emit(errMsg(fmt.Sprintf("connect to %s failed: %v", cmd.Addr, err)))
|
||||
return
|
||||
}
|
||||
mesh.HandleConn(conn, m, true)
|
||||
}()
|
||||
|
||||
case proto.CmdGetState:
|
||||
send(writeCh, proto.IpcMessage{
|
||||
Type: proto.EvtStateSnapshot,
|
||||
LocalPeer: ptr(m.Identity.PeerInfo()),
|
||||
ConnectedPeers: m.ConnectedPeers(),
|
||||
Rooms: []string{"general"},
|
||||
})
|
||||
|
||||
case proto.CmdSendFile:
|
||||
send(writeCh, errMsg("file transfer not yet implemented"))
|
||||
|
||||
default:
|
||||
send(writeCh, errMsg(fmt.Sprintf("unknown command: %s", cmd.Type)))
|
||||
}
|
||||
}
|
||||
|
||||
func send(ch chan<- []byte, msg proto.IpcMessage) {
|
||||
line, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
@@ -165,3 +170,9 @@ func errMsg(s string) proto.IpcMessage {
|
||||
}
|
||||
|
||||
func ptr[T any](v T) *T { return &v }
|
||||
|
||||
func randomHex(n int) string {
|
||||
b := make([]byte, n)
|
||||
rand.Read(b) //nolint:errcheck
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user