Skip to content

Commit b7bd1f5

Browse files
committed
Fixed broken block when data is chunked by block len
When the next chunk of data has size less than block len, but block is started, it finalized block to early that cause a wrong hash. Fixed https://github.com/catap/scala-blake3/issues/1
1 parent f16402a commit b7bd1f5

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
All notable changes to this project will be documented in this file.
44

55
## [unreleased]
6+
- Fixed an issue when chunked data by block len produced incorrect block.
67

78
## [2.5.2] - 2021-05-17
89
- Switch to scala 3.0.0.

shared/src/main/scala/ky/korins/blake3/ChunkState.scala

+3-2
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,9 @@ private[blake3] class ChunkState(
7272
def update(bytes: Array[Byte], from: Int, to: Int): Unit = {
7373
var i = from
7474

75-
var consume = Math.min(BLOCK_LEN - blockLen, to - i)
76-
if (consume < BLOCK_LEN) {
75+
val available = BLOCK_LEN - blockLen
76+
var consume = Math.min(available, to - i)
77+
if (consume < available) {
7778
System.arraycopy(bytes, i, block, blockLen, consume)
7879
blockLen += consume
7980
i += consume

shared/src/test/scala/ky/korins/blake3/Blake3Test.scala

+33
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import org.scalatest.matchers.should
1313
import org.scalatest.wordspec.AnyWordSpec
1414

1515
import scala.language.implicitConversions
16+
import scala.util.Random
1617

1718
class Blake3Test extends AnyWordSpec with should.Matchers {
1819
"Very naive test" in {
@@ -221,4 +222,36 @@ class Blake3Test extends AnyWordSpec with should.Matchers {
221222
len -= CHUNK_LEN
222223
}
223224
}
225+
226+
"Chunking data" when {
227+
"63 bytes" in {
228+
val bytes = new Array[Byte](63)
229+
Random.nextBytes(bytes)
230+
val hasher1 = Blake3.newHasher()
231+
hasher1.update(bytes)
232+
val expected = hasher1.doneHex(16)
233+
234+
val hasher2 = Blake3.newHasher()
235+
hasher2.update(bytes, 0, 32)
236+
hasher2.update(bytes, 32, 31)
237+
val actual = hasher2.doneHex(16)
238+
239+
expected shouldBe actual
240+
}
241+
242+
"64 bytes" in {
243+
val bytes = new Array[Byte](64)
244+
Random.nextBytes(bytes)
245+
val hasher1 = Blake3.newHasher()
246+
hasher1.update(bytes, 0, 64)
247+
val expected = hasher1.doneHex(16)
248+
249+
val hasher2 = Blake3.newHasher()
250+
hasher2.update(bytes, 0, 32)
251+
hasher2.update(bytes, 32, 32)
252+
val actual = hasher2.doneHex(16)
253+
254+
expected shouldBe actual
255+
}
256+
}
224257
}

0 commit comments

Comments
 (0)