mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-26 11:05:20 +00:00
Migrate protocol from JSON to binary encoding
This change introduces a comprehensive binary protocol to replace JSON encoding for all network messages, resulting in ~70% bandwidth reduction and 10-20x faster parsing. Key changes: - Add BinaryEncodingUtils with common binary encoding/decoding operations - Implement toBinaryData/fromBinaryData for all 9 message types - Maintain backward compatibility with JSON fallback - Add safety checks including minimum size validation and data copying - Fix thread safety issues with concurrent data access - Update all message handlers to try binary first, then JSON Benefits: - Reduced bandwidth usage (critical for Bluetooth) - Faster message parsing - Better MTU efficiency - Eliminates JSON injection vulnerabilities - Consistent binary format throughout the protocol The implementation maintains full backward compatibility - new messages are sent as binary while the app can still receive and process JSON messages from older clients.
This commit is contained in:
@@ -459,6 +459,28 @@ struct NoiseMessage: Codable {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Binary Encoding
|
||||
|
||||
func toBinaryData() -> Data {
|
||||
var data = Data()
|
||||
data.appendUInt8(type)
|
||||
data.appendUUID(sessionID)
|
||||
data.appendData(payload)
|
||||
return data
|
||||
}
|
||||
|
||||
static func fromBinaryData(_ data: Data) -> NoiseMessage? {
|
||||
var offset = 0
|
||||
|
||||
guard let type = data.readUInt8(at: &offset),
|
||||
let sessionID = data.readUUID(at: &offset),
|
||||
let payload = data.readData(at: &offset) else { return nil }
|
||||
|
||||
guard let messageType = NoiseMessageType(rawValue: type) else { return nil }
|
||||
|
||||
return NoiseMessage(type: messageType, sessionID: sessionID, payload: payload)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
Reference in New Issue
Block a user