Skip to content

fix(chainbase): Implicit narrowing conversion in compound assignment #6420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

ptrgits
Copy link

@ptrgits ptrgits commented Aug 12, 2025

Compound assignment statements of the form x += y or x *= y perform an implicit narrowing conversion if the type of x is narrower than the type of y. For example, x += y is equivalent to x = (T)(x + y), where T is the type of x. This can result in information loss and numeric errors such as overflows.


fix the problem, we should avoid the implicit narrowing conversion in the compound assignment. Instead of using v += 27; (which implicitly casts the result of v + 27 from int to byte), we should perform the addition in int and then explicitly cast the result to byte when assigning it back to v. This makes the narrowing conversion explicit and clear to readers and static analysis tools.

Specifically, in getBase64FromByteString, replace:

if (v < 27) {
  v += 27; //revId -> v
}

with:

if (v < 27) {
  v = (byte)(v + 27); //revId -> v
}

No new imports or method definitions are needed.

References

Compound Assignment Operators, Narrowing Primitive Conversion
SEI CERT Oracle Coding Standard for Java: NUM00-J. Detect or prevent integer overflow

@troncommons
Copy link

Hi, thank you very much for your work!
This optimization has been merged to release_v4.8.1 branch through this PR #6417, and will be included in the upcoming v4.8.1 release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants