fix: accept bytearray in ctr256_encrypt/decrypt (pyrogram compatibility) - #5
Merged
Conversation
Reviewer's GuideAdds TgCrypto-compatible bytearray support to AES-256-CTR Python bindings, including safe in-place IV/state mutation semantics, tests, docs, and version bump. Sequence diagram for ctr256_encrypt bytearray state carrysequenceDiagram
actor PythonCaller
participant ctr256_encrypt
participant BufferInput
participant tgcryptors_core
participant write_back
PythonCaller->>ctr256_encrypt: ctr256_encrypt(data,key,iv,state)
ctr256_encrypt->>BufferInput: BufferInput::from_any(data,"Data")
ctr256_encrypt->>BufferInput: BufferInput::from_any(key,"Key")
ctr256_encrypt->>BufferInput: BufferInput::from_any(iv,"IV")
ctr256_encrypt->>BufferInput: BufferInput::from_any(state,"State")
ctr256_encrypt->>BufferInput: BufferInput::as_bytes() for key
ctr256_encrypt->>BufferInput: BufferInput::as_bytes() for iv
ctr256_encrypt->>BufferInput: BufferInput::as_bytes() for state
ctr256_encrypt->>BufferInput: BufferInput::as_bytes() for data
ctr256_encrypt->>tgcryptors_core: ctr256_encrypt_into(data_slice,key_arr,iv_arr,state_val,dest)
tgcryptors_core-->>ctr256_encrypt: returns (next_iv,next_state)
ctr256_encrypt->>BufferInput: BufferInput::into_source() for iv
ctr256_encrypt->>BufferInput: BufferInput::into_source() for state
alt iv is bytearray
ctr256_encrypt->>write_back: write_back(iv_source,next_iv)
end
alt state is bytearray
ctr256_encrypt->>write_back: write_back(state_source,[next_state])
end
ctr256_encrypt-->>PythonCaller: returns ciphertext PyBytes
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="tgcryptors-python/src/lib.rs" line_range="98-109" />
<code_context>
+/// The buffer length is guaranteed to match `value` because extraction copied
+/// the exact same length and Python code cannot legally resize the object
+/// while this function holds it inside the critical section.
+fn write_back(byte_array: &Bound<'_, PyByteArray>, value: &[u8]) {
+ with_critical_section(byte_array.as_any(), || {
+ // SAFETY: the critical section prevents concurrent mutation of the
+ // buffer, and the buffer was not resized since extraction.
+ unsafe { byte_array.as_bytes_mut() }.copy_from_slice(value);
+ });
+}
</code_context>
<issue_to_address>
**suggestion (bug_risk):** write_back relies on implicit invariants about buffer length that could fail noisily if future callers misuse it.
The function depends on `value.len() == byte_array.len()`, and `copy_from_slice` will panic if that ever stops being true. Current call sites (`copy_array` / `validate_ctr_state`) enforce the invariant, but future reuse or changes to the CTR logic could easily break it. Adding an explicit `debug_assert_eq!(byte_array.len(), value.len());` before the unsafe block would make violations fail immediately and closer to the source.
```suggestion
/// Overwrite the contents of a `bytearray` with `value`.
///
/// The buffer length is guaranteed to match `value` because extraction copied
/// the exact same length and Python code cannot legally resize the object
/// while this function holds it inside the critical section.
fn write_back(byte_array: &Bound<'_, PyByteArray>, value: &[u8]) {
with_critical_section(byte_array.as_any(), || {
debug_assert_eq!(
byte_array.len(),
value.len(),
"write_back: bytearray length ({}) must match value length ({})",
byte_array.len(),
value.len()
);
// SAFETY: the critical section prevents concurrent mutation of the
// buffer, and the buffer was not resized since extraction and the
// lengths are asserted to match.
unsafe { byte_array.as_bytes_mut() }.copy_from_slice(value);
});
}
```
</issue_to_address>
### Comment 2
<location path="tests/test_python_api.py" line_range="115" />
<code_context>
+
+ self.assertEqual(plaintext, data)
+
+ def test_ctr_bytearray_mutates_iv_and_state_in_place(self) -> None:
+ data = self.data + b"xyz" # 67 bytes, not block aligned
+ iv = bytearray(self.iv_cbc)
+ state = bytearray(1)
+
+ tgcrypto.ctr256_encrypt(data, self.key, iv, state)
+
+ self.assertEqual(state[0], len(data) % 16)
+ self.assertNotEqual(iv, bytearray(self.iv_cbc))
+
def test_ige_stream_matches_one_shot(self) -> None:
</code_context>
<issue_to_address>
**suggestion (testing):** Add a complementary test that bytes inputs remain stateless and do not mutate iv/state.
This test covers in-place mutation for bytearray iv/state and the expected state offset. Please also add a test that calls `ctr256_encrypt` with iv/state (and optionally data/key) as `bytes`, asserting that those original objects remain unchanged across calls, so both mutable (bytearray) and immutable (bytes) behaviors are explicitly verified.
```suggestion
def test_ctr_bytes_do_not_mutate_iv_or_state(self) -> None:
data = self.data + b"xyz" # 67 bytes, not block aligned
iv = self.iv_cbc
state = b"\x00"
ciphertext1 = tgcrypto.ctr256_encrypt(data, self.key, iv, state)
ciphertext2 = tgcrypto.ctr256_encrypt(data, self.key, iv, state)
self.assertEqual(iv, self.iv_cbc)
self.assertEqual(state, b"\x00")
self.assertEqual(ciphertext1, ciphertext2)
def test_ige_stream_matches_one_shot(self) -> None:
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
ctr256_encrypt and ctr256_decrypt rejected bytearray arguments because the PyO3 0.29 &[u8] extractor only accepts bytes. pyrogram and its forks pass bytearray for data, key, iv, and state and rely on iv/state being mutated in place to carry the CTR counter across calls. Accept bytes or bytearray for all four arguments. bytearray iv/state are copied up front (the GIL is released during the operation) and the advanced counter and residual byte offset are written back in place afterwards, matching TgCrypto's stateful semantics. Co-authored-by: whoarchie <esanovalr.k@gmail.com>
Verify bytearray acceptance for data/key/iv/state, in-place mutation of iv/state across calls, chunked streams matching the one-shot result, a large CDN-style roundtrip, and that bytes inputs stay stateless. Co-authored-by: whoarchie <esanovalr.k@gmail.com>
Explain the TgCrypto-compatible bytearray mode: data/key/iv/state may be bytearray, and iv/state are updated in place so the stream continues across chunked calls, as pyrogram and its forks require. Co-authored-by: whoarchie <esanovalr.k@gmail.com>
Co-authored-by: whoarchie <esanovalr.k@gmail.com>
joyccn
force-pushed
the
fix/ctr-bytearray
branch
from
August 13, 2026 01:12
a8cb825 to
e8ac821
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #4.
Problem
ctr256_encrypt/ctr256_decryptrejectedbytearrayfordata/key/iv/statebecause the PyO3 0.29&[u8]extractor only acceptsbytes:pyrogram and its forks (kurigram, pyrofork, ...) always pass
bytearray— their obfuscated TCP transports and CDN downloads reuse the sameiv/stateobjects across calls and rely on them being mutated in place to carry the CTR counter forward. The crash hit at connect time, so bots could not connect at all with this library as the crypto backend.Fix
ctr256_encrypt/ctr256_decryptnow acceptbytes(zero-copy) orbytearrayfordata,key,iv, andstate.iv/statearebytearray, the advanced counter and residual byte offset are written back in place after the operation, matching TgCrypto's stateful semantics (verified against pyrogram's pyaes fallback algorithm).Verification
cargo fmtandclippy -D warningsclean.Co-authored-by: whoarchie esanovalr.k@gmail.com
Summary by Sourcery
Add TgCrypto-compatible bytearray support and in-place state carry semantics to AES-256-CTR bindings and bump the library version.
New Features:
Enhancements:
Build:
Documentation:
Tests: