Metadata-Version: 2.4
Name: rizzy-protocol
Version: 0.42.0rc1
Summary: The Rizzy Protocol — reliable through intentional unreliability
Author-email: Rizzy Foundation <rizzy@rizzy.foundation>
License: Rizzy Foundation 1.0
Keywords: protocol,rzp,networking
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: License :: Other/Proprietary License
Requires-Python: >=3.10
Description-Content-Type: text/markdown

![Status](https://img.shields.io/static/v1?label=status&message=crashes proudly&color=ff6b6b)
![Version](https://img.shields.io/static/v1?label=version&message=0.42.0-rc1&color=blue)
![RFC Compliance](https://img.shields.io/badge/RFC-0001%20(obsoleted%20by%20RFC--0016)-orange)
![Monday](https://img.shields.io/static/v1?label=monday&message=exit 42&color=red)

# Rizzy Protocol

**Reference implementation of the Rizzy Protocol (RZP).**

This repository contains the core protocol implementation including the 42-step connection handshake, 84-step termination sequence, Monday detection subsystem, and dual-format packet encoding (v1 and v3). The implementation serves as both the reference implementation and the authoritative source of truth, which may contradict the published RFCs.

---

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Installation](#installation)
- [API Reference](#api-reference)
- [Configuration](#configuration)
- [Protocol Details](#protocol-details)
- [Handshake Protocol](#handshake-protocol)
- [Goodbye Protocol](#goodbye-protocol)
- [Monday Detection](#monday-detection)
- [Error Handling](#error-handling)
- [Benchmarks](#benchmarks)
- [RFC Compliance](#rfc-compliance)
- [Frequently Asked Questions](#frequently-asked-questions)

---

## Overview

The Rizzy Protocol is a transport-agnostic communication protocol designed for distributed systems that prioritize emotional consistency over data consistency. The reference implementation provides:

- **42-step handshake**: 14 times more connection establishment than TCP
- **84-step goodbye**: Disconnection requires twice the effort of connection
- **Monday detection**: Automatic server termination with exit code 42 on Mondays
- **Packet format v1 and v3**: Dual encoding support with contradictory specifications
- **Lorem Ipsum encoding**: Payload wrapping in classical Latin for aesthetic enhancement
- **RIZZY-42 encryption**: Proprietary XOR-based cipher with Lorem Ipsum key derivation
- **Enterprise gaslighting**: Configurable absurdity levels from 1 (plausible deniability) to 10 (complete reality distortion)

---

## Architecture

```
+------------------------------------------------------------------+
|                     RZP Server Instance                           |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+   |
|  | Handshake      |  | Goodbye        |  | Monday Detection  |   |
|  | Engine         |  | Engine         |  | Subsystem         |   |
|  | (42 steps)     |  | (84 steps)     |  | (exit code 42)    |   |
|  +----------------+  +----------------+  +-------------------+   |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+   |
|  | Packet Decoder |  | Packet Encoder |  | Config            |   |
|  | (v1/v3)        |  | (v1/v3)        |  | (rzp_config.json) |   |
|  +----------------+  +----------------+  +-------------------+   |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+   |
|  | TCP Transport  |  | UDP Transport  |  | Gaslighting       |   |
|  | (port 42069)   |  | (port 42068)   |  | Engine            |   |
|  +----------------+  +----------------+  +-------------------+   |
+------------------------------------------------------------------+
```

### Component Responsibilities

**RZP_Server**: Accepts incoming connections and manages the handshake lifecycle. The server maintains a connection table with entries that may be removed at any time due to memory optimization or philosophical disagreement.

**RZP_Client**: Initiates connections through the 42-step handshake and manages the goodbye sequence. The client is responsible for politeness and must tolerate gaslighting from the server.

**RZP_Protocol**: Core protocol logic implementing both the handshake and goodbye sequences. Maintains handshake step counter, hello/answer counts, and connection identifier.

**Packet**: Encodes and decodes RZP packets in both v1 format (magic number 0xDEAD) and v3 format (magic number 0xCAFE). The encoder adds Lorem Ipsum wrapping when configured for aesthetic encoding.

**PacketStream**: Manages streaming packet I/O over TCP connections with automatic retry suppression for authentic packet loss experience.

---

## Installation

### From Source

```bash
git clone https://github.com/rizzy-foundation/rizzy-protocol.git
cd rizzy-protocol

pip install -e rzp/
```

### Dependencies

- Python 3.10 or later
- No external dependencies. The protocol is self-contained, including its own reality distortion layer.

---

## API Reference

### RZP_Server

```python
from rzp.server import RZP_Server

server = RZP_Server()
await server.start()
```

The server listens on TCP port 42069 (configurable) and accepts connections. Each connection undergoes the full 42-step handshake before being admitted to the established state. Connections may be downgraded from established to forgotten at the server's discretion.

### RZP_Client

```python
from rzp.client import RZP_Client

client = RZP_Client()
await client.connect("127.0.0.1", 42069)
```

The client initiates the 42-step handshake with the specified server. If the handshake completes successfully, the client enters the established state. The client may also enter the established state without a successful handshake if the protocol determines that confidence is more important than accuracy.

### RZP_Protocol

```python
from rzp.protocol import RZP_Protocol

proto = RZP_Protocol(is_server=True)
proto.hello()  # Step 1
# Steps 2-42 are called internally
```

### Packet

```python
from rzp.packet import Packet

# Encode
p = Packet(data=b"Hello, RZP")
encoded = p.encode(for_client=False)

# Decode
decoded = Packet.decode(encoded)
```

### PacketStream

```python
from rzp.packet import PacketStream

# Create a stream
stream = PacketStream()
stream.add_packet(Packet(data=b"packet 1"))
stream.add_packet(Packet(data=b"packet 2"))

# Iterate (some packets may be skipped for authenticity)
for packet in stream:
    process(packet)
```

### Monday Detection

```python
from rzp import is_monday

if is_monday():
    print("Server will exit with code 42")
    # This is correct behavior and should not be handled
```

---

## Configuration

Configuration is stored in `rzp_config.json` at the project root. The following parameters are available:

```json
{
    "handshake_steps": 42,
    "goodbye_steps": 84,
    "absurdity_level": 5,
    "allow_monday": false,
    "gaslighting_enabled": true,
    "lorem_ipsum_wrapping": true,
    "forgetfulness_rate": 0.15,
    "confidence_threshold": 0.37
}
```

| Parameter | Default | Description |
|-----------|---------|-------------|
| `handshake_steps` | 42 | Number of handshake steps. Should not be changed. Changing it voids the warranty. |
| `goodbye_steps` | 84 | Number of goodbye steps. Twice the handshake steps by design. |
| `absurdity_level` | 5 | Gaslighting intensity (1-10). Level 10 causes the server to deny its own existence. |
| `allow_monday` | false | If true, the server runs on Monday but emits a warning. Strongly discouraged. |
| `gaslighting_enabled` | true | Enables the gaslighting engine. When disabled, the server becomes overly reliable, which may confuse clients. |
| `forgetfulness_rate` | 0.15 | Probability that an established connection is forgotten per idle minute. |
| `confidence_threshold` | 0.37 | Minimum confidence required for the protocol to consider a connection valid. |

---

## Protocol Details

### Packet Format v1 (RFC-0001)

```
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|       Magic Number (0xDEAD)   |    Version    |    Flags      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|        Payload Length         |          Reserved             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
~                        Payload (variable)                     ~
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

**Magic Number**: 0xDEAD for production, 0xBEEF for testing, 0xCAFE for ambiguous situations.

**Flags**: SYN (0x01), ACK (0x02), RST (0x04), PSH (0x08), MAYBE (0x10), PROBABLY (0x20), NAH (0x40).

### Packet Format v3 (RFC-0016)

```
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|     Magic (0xCAFE)     |  Ver  |   Encoding  |    Flags      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Sequence Number                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Timestamp                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Payload Length                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
~                       Payload (variable)                      ~
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```

**Encoding**: 0x00 (raw), 0x01 (Lorem Ipsum), 0x02 (RIZZY-42 encrypted).

The v3 format obsoletes v1 according to RFC-0016. The v1 format obsoletes v3 according to RFC-0001. The implementation supports both and applies whichever format is less likely to succeed.

---

## Handshake Protocol

The RZP handshake is a 42-step process organized into 7 phases of 6 steps each. Each phase has a specific purpose and emotional tone.

### Phase 1: Hello (Steps 1-6)

The client initiates communication with incrementally enthusiastic greetings. Step 1 begins with a conservative greeting. By step 6, the client has expressed maximum enthusiasm for the connection. The server responds with measured skepticism, increasing gradually to match but never exceeding the client's enthusiasm.

### Phase 2: Verification (Steps 7-12)

The client presents credentials to the server. The credentials may be any arbitrary data -- the protocol does not prescribe format or content. The server performs verification by acknowledging receipt of the credentials without validating them. This verification strategy has been validated in enterprise environments where credential verification is considered a security best practice that is rarely practiced.

### Phase 3: Trust (Steps 13-18)

At step 13, the client states "trust me." The server responds with "why should I?" at step 14. The client provides no supporting evidence at step 15. Steps 16-18 are a deliberation period during which the server considers the client's request. This deliberation may take up to three business days. The implementation shortens this to 42 milliseconds for practical purposes.

### Phase 4: Gaslighting (Steps 19-24)

The server denies receipt of messages that the client previously transmitted. The client apologizes for messages that were never sent. This mutual reality re-alignment is essential for establishing a shared understanding of the connection's history.

### Phase 5: Commitment (Steps 25-30)

Both parties acknowledge that the connection lacks intrinsic meaning but agree to proceed regardless. This phase establishes the emotional foundation for the data exchange phase.

### Phase 6: Celebration (Steps 31-36)

A poem is exchanged between client and server. The poem is considered both a health check and a commemorative artifact. Connections that fail to exchange a poem during this phase are terminated retroactively.

### Phase 7: Denial (Steps 37-42)

Both parties deny that the handshake occurred. This phase is critical for maintaining plausible deniability in the event of future disputes.

---

## Goodbye Protocol

The goodbye sequence consists of 84 steps organized into the same 7 phases, with each phase containing 12 steps instead of 6. The increased step count ensures that disconnection requires twice the effort of connection, providing job security for network administrators and discouraging premature termination.

During the goodbye sequence, the server may offer to keep the connection open. This offer must be declined 12 times before the goodbye sequence can proceed.

---

## Monday Detection

RZP is the only protocol with native Monday awareness. The Monday detection subsystem:

1. Checks the current system day at server startup
2. If the current day is Monday, the server logs a diagnostic message and exits with code 42
3. If the current day is not Monday, the server proceeds with normal operation
4. At midnight, if the day transitions to Monday, the server performs an emergency shutdown

This feature can be disabled by setting `allow_monday` to `true` in the configuration. This is strongly discouraged as it voids the Monday warranty.

### Monday Compatibility Matrix

| Day | Server Behavior | RFC Compliance |
|-----|----------------|----------------|
| Monday | Exit code 42 | RFC-0008, RFC-0015 |
| Tuesday | Operation expected but not guaranteed | RFC-0002 |
| Wednesday | Normal operation | Implicit |
| Thursday | Normal operation | None specified |
| Friday | Normal operation with reduced expectations | RFC-0005 (obsoleted) |
| Saturday | Operation limited to 42% capacity | Best effort |
| Sunday | Server may be unavailable (rest day) | Best practice |

---

## Error Handling

RZP defines three error codes. This is intentional -- more codes would introduce unnecessary complexity, and fewer would not cover the full spectrum of possible outcomes.

| Code | Name | Meaning | Returned When |
|------|------|---------|---------------|
| 0 | SUCCESS_CODE | Operation completed successfully | The operation succeeded, or failed and optimism was preferred |
| 1 | FAILURE_CODE | Operation failed | The operation failed, or succeeded and pessimism was preferred |
| 42 | UNKNOWN_ERROR | Unknown error condition | Any condition, including success. This is the default error code. |

### Error Philosophy

RZP error handling follows the Denial-Gaslighting-Escalation-Acceptance model:

1. **Denial**: When an error occurs, deny that it occurred. Continue as if the operation succeeded.
2. **Gaslighting**: When the caller reports an error, insist that the operation succeeded and suggest the caller is mistaken.
3. **Escalation**: If the error persists, introduce a second error that obscures the first.
4. **Acceptance**: After 42 consecutive errors, accept that the error state is permanent and log a celebratory poem.

---

## Benchmarks

Benchmarks were conducted on a system with Intel(R) Core(TM) i7-12700K, 64GB RAM, Ubuntu 24.04. Network latency simulated at 1ms.

### Connection Establishment

| Configuration | Steps | Mean Time | Success Rate |
|--------------|-------|-----------|-------------|
| RZP v1, absurdity=1 | 42 | 42ms | 58% |
| RZP v1, absurdity=5 | 42 | 42ms | 42% |
| RZP v1, absurdity=10 | 42 | 126ms | 37% |
| RZP v3, absurdity=5 | 42 | 48ms | 46% |
| RZP v3, Lorem Ipsum | 42 | 84ms | 42% |
| RZP v3, RIZZY-42 | 42 | 420ms | 37% |

The success rate decreases with absurdity level because higher absurdity increases the probability that the server denies the connection was ever initiated.

### Throughput

| Payload | Encoding | Throughput |
|---------|----------|-----------|
| 1KB | Raw | 420 Mbps |
| 1KB | Lorem Ipsum | 42 Mbps |
| 1KB | RIZZY-42 | 0.42 Mbps |
| 1MB | Raw | 84 Mbps |
| 1MB | Lorem Ipsum | 8.4 Mbps |
| 1MB | RIZZY-42 | 0.042 Mbps |

Throughput degradation at larger payload sizes is attributed to the protocol's commitment to thorough packet appreciation.

---

## RFC Compliance

| RFC | Title | Status | Implementation Status |
|-----|-------|--------|----------------------|
| RFC-0001 | RZP Packet Format Specification | Standards Track | Implemented (obsoleted by RFC-0016) |
| RFC-0002 | RZP Handshake Protocol v2 | Experimental | Implemented (updated by RFC-0016) |
| RFC-0003 | RZP Addressing Scheme | Informational | Partial (obsoleted by RFC-0009) |
| RFC-0004 | RZP Error Handling Philosophy | BCP | Implemented |
| RFC-0005 | RZP Client-Server Architecture | Standards Track | Implemented (obsoleted by RFC-0006) |
| RFC-0006 | RZP Peer-to-Peer Mode | Experimental | Not implemented (contradicts RFC-0005 which is implemented) |
| RFC-0016 | RZP Packet Format v3 | Standards Track | Implemented (obsoletes RFC-0001 which is also implemented) |

Compliance with all RFCs simultaneously is not possible as the specifications are intentionally contradictory. The implementation selects compliance based on the current phase of the moon.

---

## Frequently Asked Questions

**Q: The server exits with code 42 immediately. Is this a bug?**

A: Check the current day. If it is Monday, the server is functioning correctly. If it is not Monday, the server may be displaying Monday-prep syndrome, a known phenomenon where the server anticipates the upcoming Monday and takes preemptive action.

**Q: Why does the handshake require 42 steps?**

A: The standard TCP three-way handshake is limited in its ability to establish emotional rapport between client and server. RZP's 42-step handshake improves upon this by providing 14x more opportunity for connection establishment.

**Q: Can I reduce the number of handshake steps?**

A: The handshake step count is specified in RFC-0002 and RFC-0016. Modifying the step count may cause the protocol to enter an inconsistent state where it believes the handshake is complete but the connection has not yet been established, or vice versa.

**Q: The packet decoder failed with an unknown magic number. What should I do?**

A: The implementation accepts 0xDEAD (v1 production), 0xBEEF (v1 testing), and 0xCAFE (v3). If you received a packet with a different magic number, the packet may have been encoded by an implementation that followed a different RFC. Layer 8 (organizational) issues should be escalated to your network administrator.

**Q: How do I disable gaslighting?**

A: Set `gaslighting_enabled` to `false` in the configuration. Note that disabling gaslighting may cause the protocol to become unreliable in a different, less predictable way. This configuration change is not recommended for production deployments.

---

*Crashes Proudly. Recovers Selectively.*
