bstkchat 2.2.0__tar.gz → 2.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bstkchat-2.3.0/PKG-INFO +147 -0
- bstkchat-2.3.0/README.md +128 -0
- bstkchat-2.3.0/bstkchat/chain.py +152 -0
- bstkchat-2.3.0/bstkchat/cli.py +1500 -0
- bstkchat-2.3.0/bstkchat/config.py +92 -0
- bstkchat-2.3.0/bstkchat.egg-info/PKG-INFO +147 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat.egg-info/SOURCES.txt +3 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/pyproject.toml +1 -1
- {bstkchat-2.2.0 → bstkchat-2.3.0}/setup.py +1 -1
- bstkchat-2.3.0/tests/test_chain.py +69 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/tests/test_cli.py +99 -0
- bstkchat-2.2.0/PKG-INFO +0 -70
- bstkchat-2.2.0/README.md +0 -51
- bstkchat-2.2.0/bstkchat/cli.py +0 -850
- bstkchat-2.2.0/bstkchat.egg-info/PKG-INFO +0 -70
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat/__init__.py +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat/crypto.py +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat.egg-info/dependency_links.txt +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat.egg-info/entry_points.txt +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat.egg-info/requires.txt +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/bstkchat.egg-info/top_level.txt +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/setup.cfg +0 -0
- {bstkchat-2.2.0 → bstkchat-2.3.0}/tests/test_crypto.py +0 -0
bstkchat-2.3.0/PKG-INFO
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bstkchat
|
|
3
|
+
Version: 2.3.0
|
|
4
|
+
Summary: A real-time Terminal-based Chatting Application using unique room IDs.
|
|
5
|
+
Author: BSTK Developers
|
|
6
|
+
Project-URL: Homepage, https://github.com/BTKcreations/BSTKCHAT
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Requires-Python: >=3.7
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
Requires-Dist: paho-mqtt>=1.6.1
|
|
14
|
+
Requires-Dist: rich>=13.0.0
|
|
15
|
+
Requires-Dist: prompt-toolkit>=3.0.0
|
|
16
|
+
Requires-Dist: cryptography>=41.0.0
|
|
17
|
+
Dynamic: author
|
|
18
|
+
Dynamic: requires-python
|
|
19
|
+
|
|
20
|
+
# BSTK Chat (`bstkchat`)
|
|
21
|
+
|
|
22
|
+
**BSTK Chat** is a real-time, zero-configuration terminal chat client with optional **AES-256-GCM end-to-end encryption (E2EE)**, Rich Markdown rendering, and a modern interactive TUI. Anyone who launches `bstkchat` and enters the same Room ID (and optional password) joins a shared room instantly—no server setup required.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Features
|
|
27
|
+
|
|
28
|
+
- **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, and `--no-tls`.
|
|
29
|
+
- **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
|
|
30
|
+
- **Encrypted File Sharing:** Send files up to 512 KB with `/send <filepath>`, verified with SHA-256 and saved safely via `/accept [id]`.
|
|
31
|
+
- **Modern Terminal UI/UX:**
|
|
32
|
+
- Non-blocking input powered by `prompt_toolkit` with `Alt+Enter` multi-line editing (or `/multiline` toggle).
|
|
33
|
+
- Live bottom status bar showing connection state, active `#room`, E2EE badge, online count, logging state, and live `typing...` indicators.
|
|
34
|
+
- Switchable toolbar themes (`/theme dark|light|ansi`) and compact single-line mode (`/compact`).
|
|
35
|
+
- Context-aware autocomplete for `/` commands, `/msg`, `/accept`, `/theme`, `/log`, and `@mentions`, plus `↑`/`↓` command history.
|
|
36
|
+
- **Rich Markdown, DMs & Presence:** Send formatted Markdown, encrypted DMs (`/msg`), audio/mention alerts (`/mute` to toggle), auto-away status, and `/who` user tables.
|
|
37
|
+
- **Decentralized Encrypted Room Chain & Peer Sync:** Every room maintains an append-only, SHA-256 hash-linked encrypted store (`~/.bstkchat/chains/<room>.json`) on each participant's device. When new peers join, online peers automatically sync missing encrypted messages (`/chain`, `/sync`, or `--no-store` to opt out).
|
|
38
|
+
- **Local Logs, History & Search:** Saves sanitized transcripts to `~/.bstkchat/logs/<room>.log` with `/history`, `/search`, `/log on|off|ephemeral`, and saved preferences in `~/.bstkchat/config.json`.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
### Option 1: Using `uv` (Recommended)
|
|
45
|
+
Run without installing:
|
|
46
|
+
```bash
|
|
47
|
+
uvx bstkchat
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or install globally:
|
|
51
|
+
```bash
|
|
52
|
+
uv tool install bstkchat
|
|
53
|
+
bstkchat
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Option 2: Using `pip`
|
|
57
|
+
```bash
|
|
58
|
+
pip install bstkchat
|
|
59
|
+
bstkchat
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Option 3: From Source
|
|
63
|
+
```bash
|
|
64
|
+
git clone https://github.com/BTKcreations/BSTKCHAT.git
|
|
65
|
+
cd BSTKCHAT
|
|
66
|
+
pip install .
|
|
67
|
+
bstkchat
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Quick Start & Examples
|
|
73
|
+
|
|
74
|
+
### 1. Start a Private Encrypted Room
|
|
75
|
+
1. Launch `bstkchat`:
|
|
76
|
+
```bash
|
|
77
|
+
bstkchat
|
|
78
|
+
```
|
|
79
|
+
2. Enter your **Nickname** (or press `Enter` for a random `User-XXX` name).
|
|
80
|
+
3. Enter a **Room ID** (e.g., `dev-sync-42`) or press `Enter` to use the generated phonetic ID (e.g., `quantum-beacon-55`).
|
|
81
|
+
4. Enter a **Room Password** to enable AES-256-GCM E2EE.
|
|
82
|
+
5. Share the **Room ID** and **Password** with your teammates—anyone with both can join and decrypt messages.
|
|
83
|
+
|
|
84
|
+
### 2. Example In-Chat Workflow
|
|
85
|
+
```text
|
|
86
|
+
# Send Rich Markdown and code snippets
|
|
87
|
+
Alice > Hey @Bob, check this: `pip install bstkchat`
|
|
88
|
+
|
|
89
|
+
# Send an encrypted private Direct Message to Bob
|
|
90
|
+
Alice > /msg Bob Can you review PR #12?
|
|
91
|
+
|
|
92
|
+
# Set your status
|
|
93
|
+
Alice > /status In a meeting
|
|
94
|
+
|
|
95
|
+
# Switch to another encrypted room (use quotes for passwords with spaces)
|
|
96
|
+
Alice > /room release-ops "my secret passphrase"
|
|
97
|
+
|
|
98
|
+
# Check who is online
|
|
99
|
+
Alice > /who
|
|
100
|
+
|
|
101
|
+
# Pause local logging
|
|
102
|
+
Alice > /log off
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## Use Cases
|
|
108
|
+
|
|
109
|
+
- **Quick Developer Syncs:** Spin up a temporary room in seconds from any terminal without opening a browser or creating an account.
|
|
110
|
+
- **Pair Programming & Code Sharing:** Share formatted Markdown and code snippets directly in the terminal while staying in your coding workflow.
|
|
111
|
+
- **Ad-Hoc Encrypted Discussions:** Use a shared passphrase for private conversations where payloads are encrypted before leaving your terminal.
|
|
112
|
+
- **Remote / SSH / Headless Environments:** Chat from minimal Linux/Windows/macOS terminals or over SSH sessions where GUI chat apps aren't available.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Slash Commands
|
|
117
|
+
|
|
118
|
+
| Command | Description |
|
|
119
|
+
| :--- | :--- |
|
|
120
|
+
| `/help` | Displays a formatted table of all available commands |
|
|
121
|
+
| `/room <id> [password\|--lock]` | Switches rooms; use `--lock` to prompt for password without saving it in history |
|
|
122
|
+
| `/nick <name>` | Changes your nickname and notifies peers in the room |
|
|
123
|
+
| `/msg <user> <message>` | Sends an encrypted private direct message (DM) to a user |
|
|
124
|
+
| `/send <filepath>` | Sends an encrypted file (up to 512 KB) with SHA-256 verification |
|
|
125
|
+
| `/accept [id]` | Accepts a pending file transfer and saves it to `~/Downloads/bstkchat/` |
|
|
126
|
+
| `/status <text>` | Sets your custom status message (e.g., `AFK`, `Coding`) |
|
|
127
|
+
| `/who` or `/users` | Lists all online participants, statuses, and last-seen times |
|
|
128
|
+
| `/invite` | Prints a copyable `bstkchat --room ...` command to invite others |
|
|
129
|
+
| `/history [N]` | Displays the last `N` lines (default 15) from the room's local log |
|
|
130
|
+
| `/search <query>` | Searches the current room's local log file |
|
|
131
|
+
| `/chain` | Shows the decentralized room chain block count, integrity check, and path |
|
|
132
|
+
| `/sync [N]` | Requests up to `N` missing encrypted messages from online peers |
|
|
133
|
+
| `/log [on\|off\|ephemeral]` | Controls local logging (`ephemeral` deletes the room log on exit) |
|
|
134
|
+
| `/mute` | Toggles terminal bell alerts for mentions, DMs, and file offers |
|
|
135
|
+
| `/compact` | Toggles compact single-line message rendering |
|
|
136
|
+
| `/multiline` | Toggles multi-line input (`Enter` = newline, `Alt+Enter` = send) |
|
|
137
|
+
| `/theme <dark\|light\|ansi>` | Switches the bottom status bar theme |
|
|
138
|
+
| `/clear` | Clears the terminal screen and redraws the room banner |
|
|
139
|
+
| `/exit` or `/quit` | Announces departure and exits cleanly |
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Security Notes
|
|
144
|
+
|
|
145
|
+
- **Password-protected rooms** derive a 256-bit key with `scrypt` and encrypt each message using **AES-256-GCM** with a unique random 96-bit nonce and room-topic AAD.
|
|
146
|
+
- **Public rooms (no password)** still use a room-derived key for transport formatting, so anyone who knows the Room ID can read messages—always set a password for confidential chats.
|
|
147
|
+
- **Local logs** are stored in plain text under `~/.bstkchat/logs/` when logging is enabled; use `/log off` if you do not want transcripts saved to disk.
|
bstkchat-2.3.0/README.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# BSTK Chat (`bstkchat`)
|
|
2
|
+
|
|
3
|
+
**BSTK Chat** is a real-time, zero-configuration terminal chat client with optional **AES-256-GCM end-to-end encryption (E2EE)**, Rich Markdown rendering, and a modern interactive TUI. Anyone who launches `bstkchat` and enters the same Room ID (and optional password) joins a shared room instantly—no server setup required.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **Zero Configuration + CLI Flags:** Connects automatically over MQTT (`broker.hivemq.com`) with TLS (`8883`) enabled by default, or use `--nick`, `--room`, `--password`, `--broker`, `--port`, and `--no-tls`.
|
|
10
|
+
- **End-to-End Encryption (E2EE):** Protect rooms with a password using `scrypt` key derivation, per-message random 96-bit nonces, **AES-256-GCM** authenticated encryption, and topic-bound AAD.
|
|
11
|
+
- **Encrypted File Sharing:** Send files up to 512 KB with `/send <filepath>`, verified with SHA-256 and saved safely via `/accept [id]`.
|
|
12
|
+
- **Modern Terminal UI/UX:**
|
|
13
|
+
- Non-blocking input powered by `prompt_toolkit` with `Alt+Enter` multi-line editing (or `/multiline` toggle).
|
|
14
|
+
- Live bottom status bar showing connection state, active `#room`, E2EE badge, online count, logging state, and live `typing...` indicators.
|
|
15
|
+
- Switchable toolbar themes (`/theme dark|light|ansi`) and compact single-line mode (`/compact`).
|
|
16
|
+
- Context-aware autocomplete for `/` commands, `/msg`, `/accept`, `/theme`, `/log`, and `@mentions`, plus `↑`/`↓` command history.
|
|
17
|
+
- **Rich Markdown, DMs & Presence:** Send formatted Markdown, encrypted DMs (`/msg`), audio/mention alerts (`/mute` to toggle), auto-away status, and `/who` user tables.
|
|
18
|
+
- **Decentralized Encrypted Room Chain & Peer Sync:** Every room maintains an append-only, SHA-256 hash-linked encrypted store (`~/.bstkchat/chains/<room>.json`) on each participant's device. When new peers join, online peers automatically sync missing encrypted messages (`/chain`, `/sync`, or `--no-store` to opt out).
|
|
19
|
+
- **Local Logs, History & Search:** Saves sanitized transcripts to `~/.bstkchat/logs/<room>.log` with `/history`, `/search`, `/log on|off|ephemeral`, and saved preferences in `~/.bstkchat/config.json`.
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
### Option 1: Using `uv` (Recommended)
|
|
26
|
+
Run without installing:
|
|
27
|
+
```bash
|
|
28
|
+
uvx bstkchat
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Or install globally:
|
|
32
|
+
```bash
|
|
33
|
+
uv tool install bstkchat
|
|
34
|
+
bstkchat
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### Option 2: Using `pip`
|
|
38
|
+
```bash
|
|
39
|
+
pip install bstkchat
|
|
40
|
+
bstkchat
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Option 3: From Source
|
|
44
|
+
```bash
|
|
45
|
+
git clone https://github.com/BTKcreations/BSTKCHAT.git
|
|
46
|
+
cd BSTKCHAT
|
|
47
|
+
pip install .
|
|
48
|
+
bstkchat
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## Quick Start & Examples
|
|
54
|
+
|
|
55
|
+
### 1. Start a Private Encrypted Room
|
|
56
|
+
1. Launch `bstkchat`:
|
|
57
|
+
```bash
|
|
58
|
+
bstkchat
|
|
59
|
+
```
|
|
60
|
+
2. Enter your **Nickname** (or press `Enter` for a random `User-XXX` name).
|
|
61
|
+
3. Enter a **Room ID** (e.g., `dev-sync-42`) or press `Enter` to use the generated phonetic ID (e.g., `quantum-beacon-55`).
|
|
62
|
+
4. Enter a **Room Password** to enable AES-256-GCM E2EE.
|
|
63
|
+
5. Share the **Room ID** and **Password** with your teammates—anyone with both can join and decrypt messages.
|
|
64
|
+
|
|
65
|
+
### 2. Example In-Chat Workflow
|
|
66
|
+
```text
|
|
67
|
+
# Send Rich Markdown and code snippets
|
|
68
|
+
Alice > Hey @Bob, check this: `pip install bstkchat`
|
|
69
|
+
|
|
70
|
+
# Send an encrypted private Direct Message to Bob
|
|
71
|
+
Alice > /msg Bob Can you review PR #12?
|
|
72
|
+
|
|
73
|
+
# Set your status
|
|
74
|
+
Alice > /status In a meeting
|
|
75
|
+
|
|
76
|
+
# Switch to another encrypted room (use quotes for passwords with spaces)
|
|
77
|
+
Alice > /room release-ops "my secret passphrase"
|
|
78
|
+
|
|
79
|
+
# Check who is online
|
|
80
|
+
Alice > /who
|
|
81
|
+
|
|
82
|
+
# Pause local logging
|
|
83
|
+
Alice > /log off
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Use Cases
|
|
89
|
+
|
|
90
|
+
- **Quick Developer Syncs:** Spin up a temporary room in seconds from any terminal without opening a browser or creating an account.
|
|
91
|
+
- **Pair Programming & Code Sharing:** Share formatted Markdown and code snippets directly in the terminal while staying in your coding workflow.
|
|
92
|
+
- **Ad-Hoc Encrypted Discussions:** Use a shared passphrase for private conversations where payloads are encrypted before leaving your terminal.
|
|
93
|
+
- **Remote / SSH / Headless Environments:** Chat from minimal Linux/Windows/macOS terminals or over SSH sessions where GUI chat apps aren't available.
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## Slash Commands
|
|
98
|
+
|
|
99
|
+
| Command | Description |
|
|
100
|
+
| :--- | :--- |
|
|
101
|
+
| `/help` | Displays a formatted table of all available commands |
|
|
102
|
+
| `/room <id> [password\|--lock]` | Switches rooms; use `--lock` to prompt for password without saving it in history |
|
|
103
|
+
| `/nick <name>` | Changes your nickname and notifies peers in the room |
|
|
104
|
+
| `/msg <user> <message>` | Sends an encrypted private direct message (DM) to a user |
|
|
105
|
+
| `/send <filepath>` | Sends an encrypted file (up to 512 KB) with SHA-256 verification |
|
|
106
|
+
| `/accept [id]` | Accepts a pending file transfer and saves it to `~/Downloads/bstkchat/` |
|
|
107
|
+
| `/status <text>` | Sets your custom status message (e.g., `AFK`, `Coding`) |
|
|
108
|
+
| `/who` or `/users` | Lists all online participants, statuses, and last-seen times |
|
|
109
|
+
| `/invite` | Prints a copyable `bstkchat --room ...` command to invite others |
|
|
110
|
+
| `/history [N]` | Displays the last `N` lines (default 15) from the room's local log |
|
|
111
|
+
| `/search <query>` | Searches the current room's local log file |
|
|
112
|
+
| `/chain` | Shows the decentralized room chain block count, integrity check, and path |
|
|
113
|
+
| `/sync [N]` | Requests up to `N` missing encrypted messages from online peers |
|
|
114
|
+
| `/log [on\|off\|ephemeral]` | Controls local logging (`ephemeral` deletes the room log on exit) |
|
|
115
|
+
| `/mute` | Toggles terminal bell alerts for mentions, DMs, and file offers |
|
|
116
|
+
| `/compact` | Toggles compact single-line message rendering |
|
|
117
|
+
| `/multiline` | Toggles multi-line input (`Enter` = newline, `Alt+Enter` = send) |
|
|
118
|
+
| `/theme <dark\|light\|ansi>` | Switches the bottom status bar theme |
|
|
119
|
+
| `/clear` | Clears the terminal screen and redraws the room banner |
|
|
120
|
+
| `/exit` or `/quit` | Announces departure and exits cleanly |
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Security Notes
|
|
125
|
+
|
|
126
|
+
- **Password-protected rooms** derive a 256-bit key with `scrypt` and encrypt each message using **AES-256-GCM** with a unique random 96-bit nonce and room-topic AAD.
|
|
127
|
+
- **Public rooms (no password)** still use a room-derived key for transport formatting, so anyone who knows the Room ID can read messages—always set a password for confidential chats.
|
|
128
|
+
- **Local logs** are stored in plain text under `~/.bstkchat/logs/` when logging is enabled; use `/log off` if you do not want transcripts saved to disk.
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Decentralized, tamper-evident encrypted hash-chain storage for BSTK Chat rooms."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
from typing import Dict, List, Optional, Set, Tuple
|
|
8
|
+
|
|
9
|
+
from bstkchat.crypto import sanitize_room_id
|
|
10
|
+
|
|
11
|
+
GENESIS_HASH = "GENESIS"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def compute_block_hash(block: dict) -> str:
|
|
15
|
+
"""Computes the SHA-256 integrity hash for a chain block."""
|
|
16
|
+
payload = "|".join([
|
|
17
|
+
str(block.get("prev_hash", GENESIS_HASH)),
|
|
18
|
+
str(block.get("id", "")),
|
|
19
|
+
f"{float(block.get('ts', 0.0)):.6f}",
|
|
20
|
+
str(block.get("time", "")),
|
|
21
|
+
str(block.get("sender", "")),
|
|
22
|
+
str(block.get("type", "message")),
|
|
23
|
+
str(block.get("ciphertext", "")),
|
|
24
|
+
])
|
|
25
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RoomChain:
|
|
29
|
+
"""Thread-safe, append-only encrypted message chain stored per room."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, room_id: str, store_dir: str = "", enabled: bool = True):
|
|
32
|
+
self.room_id = sanitize_room_id(room_id)
|
|
33
|
+
self.enabled = enabled
|
|
34
|
+
self._lock = threading.Lock()
|
|
35
|
+
self.store_dir = store_dir or os.path.expanduser("~/.bstkchat/chains")
|
|
36
|
+
self.filepath = os.path.join(self.store_dir, f"{self.room_id}.json")
|
|
37
|
+
self.blocks: List[dict] = []
|
|
38
|
+
self._seen_ids: Set[str] = set()
|
|
39
|
+
if self.enabled:
|
|
40
|
+
self._load()
|
|
41
|
+
|
|
42
|
+
def _load(self) -> None:
|
|
43
|
+
if not os.path.exists(self.filepath):
|
|
44
|
+
return
|
|
45
|
+
try:
|
|
46
|
+
with open(self.filepath, "r", encoding="utf-8") as f:
|
|
47
|
+
data = json.load(f)
|
|
48
|
+
if isinstance(data, list):
|
|
49
|
+
valid_blocks = [
|
|
50
|
+
b for b in data
|
|
51
|
+
if isinstance(b, dict) and b.get("id") and b.get("hash") == compute_block_hash(b)
|
|
52
|
+
]
|
|
53
|
+
valid_blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
|
|
54
|
+
self.blocks = valid_blocks
|
|
55
|
+
self._seen_ids = {str(b["id"]) for b in valid_blocks}
|
|
56
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
57
|
+
self.blocks = []
|
|
58
|
+
self._seen_ids = set()
|
|
59
|
+
|
|
60
|
+
def _save(self) -> None:
|
|
61
|
+
if not self.enabled:
|
|
62
|
+
return
|
|
63
|
+
try:
|
|
64
|
+
os.makedirs(os.path.dirname(self.filepath), exist_ok=True)
|
|
65
|
+
with open(self.filepath, "w", encoding="utf-8") as f:
|
|
66
|
+
json.dump(self.blocks, f, indent=2)
|
|
67
|
+
except OSError:
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
def append_message(
|
|
71
|
+
self,
|
|
72
|
+
msg_id: str,
|
|
73
|
+
ts: float,
|
|
74
|
+
time_str: str,
|
|
75
|
+
sender: str,
|
|
76
|
+
msg_type: str,
|
|
77
|
+
ciphertext: str,
|
|
78
|
+
) -> Optional[dict]:
|
|
79
|
+
"""Creates, hashes, and persists a new encrypted block if not already present."""
|
|
80
|
+
if not self.enabled or not msg_id:
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
with self._lock:
|
|
84
|
+
if msg_id in self._seen_ids:
|
|
85
|
+
return None
|
|
86
|
+
|
|
87
|
+
prev_hash = self.blocks[-1]["hash"] if self.blocks else GENESIS_HASH
|
|
88
|
+
block = {
|
|
89
|
+
"id": msg_id,
|
|
90
|
+
"ts": float(ts),
|
|
91
|
+
"time": time_str,
|
|
92
|
+
"sender": sender,
|
|
93
|
+
"type": msg_type,
|
|
94
|
+
"ciphertext": ciphertext,
|
|
95
|
+
"prev_hash": prev_hash,
|
|
96
|
+
}
|
|
97
|
+
block["hash"] = compute_block_hash(block)
|
|
98
|
+
|
|
99
|
+
self.blocks.append(block)
|
|
100
|
+
self.blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
|
|
101
|
+
self._seen_ids.add(msg_id)
|
|
102
|
+
self._save()
|
|
103
|
+
return block
|
|
104
|
+
|
|
105
|
+
def merge_blocks(self, incoming_blocks: List[dict]) -> List[dict]:
|
|
106
|
+
"""Verifies hashes, deduplicates, merges, and persists blocks from peers."""
|
|
107
|
+
if not self.enabled or not incoming_blocks:
|
|
108
|
+
return []
|
|
109
|
+
|
|
110
|
+
added: List[dict] = []
|
|
111
|
+
with self._lock:
|
|
112
|
+
for block in incoming_blocks:
|
|
113
|
+
if not isinstance(block, dict):
|
|
114
|
+
continue
|
|
115
|
+
msg_id = str(block.get("id", ""))
|
|
116
|
+
if not msg_id or msg_id in self._seen_ids:
|
|
117
|
+
continue
|
|
118
|
+
if block.get("hash") != compute_block_hash(block):
|
|
119
|
+
continue
|
|
120
|
+
self.blocks.append(block)
|
|
121
|
+
self._seen_ids.add(msg_id)
|
|
122
|
+
added.append(block)
|
|
123
|
+
|
|
124
|
+
if added:
|
|
125
|
+
self.blocks.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
|
|
126
|
+
self._save()
|
|
127
|
+
|
|
128
|
+
added.sort(key=lambda b: (float(b.get("ts", 0.0)), str(b.get("id", ""))))
|
|
129
|
+
return added
|
|
130
|
+
|
|
131
|
+
def get_known_ids(self, limit: int = 500) -> List[str]:
|
|
132
|
+
with self._lock:
|
|
133
|
+
return [str(b["id"]) for b in self.blocks[-limit:]]
|
|
134
|
+
|
|
135
|
+
def get_missing_blocks(self, peer_known_ids: Set[str], limit: int = 100) -> List[dict]:
|
|
136
|
+
with self._lock:
|
|
137
|
+
missing = [b for b in self.blocks if str(b.get("id")) not in peer_known_ids]
|
|
138
|
+
return missing[-limit:]
|
|
139
|
+
|
|
140
|
+
def get_recent_blocks(self, limit: int = 20) -> List[dict]:
|
|
141
|
+
if limit <= 0:
|
|
142
|
+
return []
|
|
143
|
+
with self._lock:
|
|
144
|
+
return list(self.blocks[-limit:])
|
|
145
|
+
|
|
146
|
+
def verify_integrity(self) -> Tuple[bool, int]:
|
|
147
|
+
"""Verifies every block's SHA-256 hash in the local chain."""
|
|
148
|
+
with self._lock:
|
|
149
|
+
for block in self.blocks:
|
|
150
|
+
if block.get("hash") != compute_block_hash(block):
|
|
151
|
+
return False, len(self.blocks)
|
|
152
|
+
return True, len(self.blocks)
|