1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Protocol 6: node identities, error codes, Synchronous, schema v8, examples

- Protocol 5: a client authenticates as a node (Node), its pushes go to the
  section's DefaultTopic unless they name one; old Identities refused at
  start with what to write instead.
- Topics listed by name, ids picked and kept by the server; nodes come from
  client sections, [BakaShrot.Nodes] optional, AcceptNodes = * by default.
- Protocol 6: every refusal carries a code, every client failure too
  (BakaShrot_ErrorCodes.pbi, BakaShrot_GetLastError(), ErrorCode in Python);
  nothing reconnects by itself, delivery is at least once.
- [BakaShrot.Server] Synchronous = FULL (default) or NORMAL, benchmarked.
- Schema v8: browse table and browse_messages view for database tools.
- Tools renamed BakaShrot<Name>, wait for Enter when started from Explorer.
- Examples/SingleServer: a server and a client with scripts (example keys,
  public on purpose).
- Restart-Test.ps1: servers killed mid-traffic and mid-catch-up.
- Docs: one server per node rule, DatabaseError() checked per thread,
  release notes' Compatibility section, Notes "Right now".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH
This commit is contained in:
2026-11-09 23:57:55 +01:00
parent df61ef9719
commit 488ffe4bc8
67 changed files with 3163 additions and 1029 deletions
+8 -7
View File
@@ -33,7 +33,7 @@ keys sit in plain-text ini files (see the end).
| libsodium | Wrapper | Notes |
|---|---|---|
| `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. |
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/KeyGen`. |
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. |
| `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. |
| `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. |
| `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. |
@@ -69,9 +69,10 @@ keys sit in plain-text ini files (see the end).
- **Connection keys: X25519**, made for each connection by both ends, the
secrets wiped once the cipher has its keys. So a recorded connection
can't be decrypted later, even with both identity keys (forward secrecy).
- **Generated** by `Tools/KeyGen`, which `Build.ps1` runs on every build.
- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs
on every build.
- **Wiping:**
- Wiped from memory after use: KeyGen; a server's key when it stops, and
- Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and
its peer links'; every connection's keys when it ends.
- Not wiped: the client DLL's global copy of its private key, and the
config structures holding the Base64 text.
@@ -91,11 +92,11 @@ See `Design/Packets.md` for the packets, `Connections.pbi` for the code.
The client knows the server's public key beforehand.
1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's
identity (topic, node), its Base64 public key, and the public half of a
key pair it made for this connection.
node (the one it writes as), its Base64 public key, and the public half
of a key pair it made for this connection.
2. The server opens it (another server can't: abort), decodes the key and
checks that a `[BakaShrot.Client.<name>]` lists both this key and this
identity.
checks that a `[BakaShrot.Client.<name>]` has this `Node` and lists this
key.
3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce,
the public half of the server's own pair for this connection, and the
server's signature of the transcript.
+31 -17
View File
@@ -26,6 +26,8 @@ Reference for working on BakaShrot's networking. Related docs:
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` |
| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` |
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
@@ -74,8 +76,9 @@ Reference for working on BakaShrot's networking. Related docs:
array, read in order with PB-MessagePack:
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
"BSHT").
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4:
attachments; 3: the Hello sealed, a key per connection, everything
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6:
refusals carry a code; 5: the Hello carries the node only, the default
topic is the server's; 4: attachments; 3: the Hello sealed, a key per connection, everything
after the ChallengeRequest encrypted, times; 2 had topics and nodes by
name, in plain text; 1 had ids only).
3. `PacketType` (integer), one of the ids below.
@@ -90,10 +93,13 @@ Reference for working on BakaShrot's networking. Related docs:
### Topics and nodes: names and ids
- **Each server has its own ids** (0-65535) for topics and nodes, and the
config can name them (`[BakaShrot.Topics]`, `[BakaShrot.Nodes]`). The
**name is what's shared**: "logs" can be 1 on one server and 200 on
another.
- **Each server has its own ids** (0-65535) for topics and nodes, and
gives them to the names: the config lists the topics
(`[BakaShrot.Topics]`), the nodes come from the sections that define
them (its own, its peers', its clients') and optionally
`[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new
one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is
what's shared**: "logs" can be 1 on one server and 200 on another.
- **A ref** is how a packet gives a topic or node: a name (1-64 of
`A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits,
which always means that id on the receiving server. An unnamed topic or
@@ -105,7 +111,7 @@ Reference for working on BakaShrot's networking. Related docs:
- **Only what's named on both servers replicates.** Unnamed topics and
nodes, and names the other server doesn't have, are dropped, unless the
receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard
(`*`, `sensors.*`) matching it: it's then added there with an id of its
(`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its
own. The sync state lists every name the receiver takes, and its
wildcards, so the sender only sends those and nothing gets refused at
every check-in.
@@ -119,7 +125,7 @@ over its own link to another server.
|---|---|---|---|---|
| 0 | None | | Never valid. | |
| 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | |
| 4 | ClientHello | C→S | `ClientTopic` str (ref), `ClientNode` str (ref), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
| 7 | AuthAccepted | S→C | None. | |
@@ -127,7 +133,7 @@ over its own link to another server.
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | |
| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `Reason` str, for logs and humans | |
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused |
@@ -165,7 +171,13 @@ the client's), and keeps that time on every server it's replicated to.
- **Refuse or abort:**
- **Refuse** (RequestRefused, the connection stays open) for things that
are valid but not allowed: permissions, no message found, too big,
a failed query, a regular client sending replication packets.
a failed query, a regular client sending replication packets. Each with
a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName,
NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest,
DataMismatch, QueryFailed, ServerError. Clients get them from
`BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with
their own codes (100+) for what never reached the server or broke the
connection.
- **Abort** (the connection is closed) for anything malformed or out of
order: an invalid frame or packet, a packet type that isn't expected at
that point, an answer to a different request, a timeout during the
@@ -187,12 +199,12 @@ the client's), and keeps that time on every server it's replicated to.
```
client: knows the server's Ed25519 public key (ServerPublicKey),
makes a key pair for this connection
C -> S ClientHello identity (topic and node refs) + Base64 public key
C -> S ClientHello node (ref, the one it writes as) + Base64 public key
+ the public half of the client's pair,
sealed for the server's public key
server: opens it (or aborts: not for this server), the refs must
resolve to its ids, the key must decode to 32 bytes, and one
[BakaShrot.Client.<name>] must list both this key and this identity
server: opens it (or aborts: not for this server), the node must
resolve to its id, the key must decode to 32 bytes, and one
[BakaShrot.Client.<name>] must have this Node and list this key
S -> C ChallengeRequest fresh random challenge + nonce, the public half of
the server's pair, and the server's signature of
the transcript (in plain text)
@@ -215,14 +227,16 @@ server's session halves, the challenge, the nonce.
connection:
- Its **permissions**, from the matching client section: `AllowRead`,
`AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters
(default: the topics of its `Identities`).
- Whether it's a **peer**: its key and identity match a
(default: its `DefaultTopic`, nothing without one), and that
`DefaultTopic`: the topic of its pushes that don't name one.
- Whether it's a **peer**: its key and node match a
`[BakaShrot.Peer.<name>]`, and then its `AcceptTopics`.
### Client requests
```
PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), at most
PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic,
refused without one), at most
#BakaShrot_MaxMessageSize. JSON or not: stored as
is, SQLite flags it in is_json
-> stored under t and the authenticated node with the
+16 -13
View File
@@ -18,14 +18,14 @@ warning, not an error).
Its smoke test, from the release folder, on one server with a throwaway
database:
- generates keys with `KeyGen.exe`, writes a server and a client config;
- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config;
- pushes two messages, reads the latest back by name, reads both with
`GetMessages.exe`, resolves a name, queries them through the `messages`
`BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages`
view with `is_json = 1`;
- if `python` is on the PATH, reads them and pushes one with
`python\bakashrot.py`;
- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back
identical with `GetAttachment.exe`;
- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back
identical with `BakaShrotGetAttachment.exe`;
- then force-kills the server and deletes everything.
The end-to-end tests in `Tests/` cover much more (names, replication, big
@@ -79,10 +79,12 @@ in `Tests/` already, to be pointed at the release instead.
first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a
trigger in the same transaction as the messages, and every check-in
with a peer starts from both sync states, read from the databases. A
killed process loses nothing committed, even with `synchronous =
NORMAL` (only a power loss or an OS crash can). **Not tested against
the release yet**, `Names-Test.ps1` restarts a server but doesn't check
these.
killed process loses nothing committed, whatever `Synchronous` says
(with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by
`Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight,
once in the middle of a catch-up, both directions, all hold. With
`BenchServer.exe` (the same server code plus a stop file), not the
release's exe itself.
4. **A clean shutdown**: the release server only stops from its console
(`quit`), so the test force-kills it, and the clean path never runs.
Needs a way to stop it without a console: a stop file like
@@ -108,12 +110,12 @@ in `Tests/` already, to be pointed at the release instead.
- a 1 MB message reads back whole, on both servers;
- a JSON query over non-JSON rows without `is_json = 1` is refused with
SQLite's error, not answered with no rows (fixed, see below).
9. **Every shipped tool runs once**: `ListNames`, `GetMessages --follow`
9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow`
(picks up a new push, exits 1 once the server is gone) aren't yet.
10. **Version hygiene**:
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
- the release commit is tagged (`v1.0.0`), the version comes from it;
- `VERSION.txt` gives the protocol version (4) and the runtime needed;
- `VERSION.txt` gives the protocol version (5 now) and the runtime needed;
- the Python client is checked on the oldest version it claims (3.8),
not only on the latest (3.14 here).
@@ -189,8 +191,9 @@ Not smoke-test items, but what the "1.0" label would promise. From
Fixed (protocol 3).
- Messages aren't signed by the node that first wrote them: a peer is
trusted with what it replicates (`Design/ReplicationIssues.md` #3).
- `synchronous = NORMAL`: the last commits can be lost on a power loss,
decide if that's fine (`Design/StorageConcurrency.md`).
- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~
Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default
(`Design/StorageConcurrency.md`).
Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9).
@@ -213,7 +216,7 @@ Notes for when the builds move to a pipeline.
- `Build.ps1` ends by running the server, which waits on its console:
needs a `-NoRun` switch. It also writes private keys into `Build\`,
which must never be published as an artifact.
- The tests use fixed ports (12399 for the release, 12401-12414 for
- The tests use fixed ports (12399 for the release, 12401-12416 for
`Tests/`): parallel jobs on one runner collide, make them parameters
or pick free ones.
- One entry point that runs every test (`Tests/*.ps1`, the handshake
+11 -5
View File
@@ -7,12 +7,18 @@ behind on, with their original ids. Each peer does the same over its own link.
Issues below are roughly ordered by how much they matter.
## 1. Drift: the same message id with different content (accepted for now)
## 1. Drift: the same message id with different content (ruled out by config)
**When:** the same topic/node id is written to on two servers, for example
when a client identity is registered on both and pushes to each while they
can't reach each other. This is a configuration issue that """shouldn't"""
happen in real use.
**The rule: a node pushes to one server.** Each client node has its
`[BakaShrot.Client.<name>]` section (its `Node`) on one server only, the
one it pushes to; the other servers get its messages by replication. Then
every topic/node pair has a single writer and this can't happen. Reading
from any server is fine, only pushing matters. Breaking the rule isn't
detected: it's the config's to keep.
**When it would happen:** the same topic/node id written to on two
servers, for example a client node registered on both, pushing to each
while they can't reach each other.
**What happens:** both servers are at `1:2#1`, the link drops, then:
+47 -16
View File
@@ -37,15 +37,47 @@ not done yet: `Design/Suggestions.md`.
## WAL and the write mutex (2026-11-07)
- **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with
`synchronous = NORMAL` on every connection (`#BakaShrot_Storage_Synchronous`
in `Storage.pbi`). Readers no longer block the writer: a 0.5 s raw query
used to stall pushes for seconds and once made one fail with "database is
locked", now pushes run next to it at full speed.
- **The tradeoff of NORMAL:** commits are only synced at checkpoints. The
file can't get corrupted, but the last commits before a power loss or an
OS crash can be lost. Those messages were acknowledged and maybe already
replicated, so their ids could be handed out again: drift
(`ReplicationIssues.md` #1). Set it to `FULL` to sync every commit again.
the config's `synchronous` on every connection (see below). Readers no
longer block the writer: a 0.5 s raw query used to stall pushes for
seconds and once made one fail with "database is locked", now pushes run
next to it at full speed.
- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09,
`FULL` by default (it was `NORMAL`, fixed). The root sets
`BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any
connection. `OFF` is refused (a power loss could corrupt the file),
`EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory
sync for the other journal modes).
- `FULL`: every commit flushes the WAL. An acknowledged push survives a
power loss or an OS crash. The flush is per transaction, so a group
commit's pushes share it.
- `NORMAL`: the WAL is only flushed at checkpoints (about every second,
`Writer.pbi`). The file can't get corrupted, but the last second or so
of commits before a power loss or an OS crash can be lost. Those
messages were acknowledged and maybe already replicated, so their ids
could be handed out again: drift (`ReplicationIssues.md` #1).
### Measured (2026-11-09)
`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`,
4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose
virtual disk flushes in 0.60 ms (p99 0.78 ms).
| | OFF | NORMAL | FULL | EXTRA |
|---|---|---|---|---|
| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 |
| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms |
| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 |
| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms |
| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms |
| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL |
No failed pushes, replication kept up in every case. `FULL`'s cost is the
disk's flush time: one client pushing one message at a time gets about
1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes
through the group commit, so the total drops much less (half here). On a
server SSD with power-loss protection a flush is far under 0.1 ms (close
to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for
one sequential client): time one on the target machine to know.
- **`BakaShrot_Storage_WriteMutex`** around every write. A connection that
finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10...
ms) and retries; with 10+ threads pushing, that's where the time went, and
@@ -137,12 +169,11 @@ ids exactly 1-800 on both servers.
the push or batch is refused and retried at the next check-in for
replication. Fine at current loads; decide later whether pushes should
retry.
- **Whether PureBasic's `DatabaseError()` is per thread** in thread-safe
mode. If it's shared by the whole program, an error message could show up
in the wrong thread's log or refusal. The data isn't affected.
`RunReadOnlyQuery()` only checks it after reading the rows on Linux, where
it could refuse a valid query because of another thread's error. On
Windows it asks SQLite instead (`sqlite3_errcode()` on its own
connection), see `Design/Release.md`.
- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in
thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two
threads failing on their own connections 20,000 times each never saw the
other's message. `sqlite3_errmsg16()` on the connection gives the same
text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors
`DatabaseError()` doesn't report at all, see `Design/Release.md`.)
- **A single storage thread with a job queue,** only if writes ever become
the bottleneck. SQLite only has one writer anyway.
+3 -5
View File
@@ -104,11 +104,9 @@ protocol change).
## 3. Smaller ones
- **Decide on `synchronous = NORMAL`** (`#BakaShrot_Storage_Synchronous`):
the last commits before a power loss or an OS crash can be lost, and their
ids handed out again (drift). With group commit, `FULL` costs one sync per
transaction, not per push, so it may cost much less than it used to: worth
one benchmark run before deciding.
- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config
option (`Synchronous`), `FULL` by default, measured in
`Design/StorageConcurrency.md`.
- **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07),
but the `Libs\` zips for libsodium and SQLite are gone: it only works while
the extracted DLLs are still in `Libs\*d`.