Skip to content

Commit 1131950

Browse files
committed
#73 Add input checks for plain radix tree leaf adding
1 parent a0af5f5 commit 1131950

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

src/main/java/org/unicitylabs/sdk/smt/radix/SparseMerkleTree.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import org.unicitylabs.sdk.util.BitString;
88

99
import java.math.BigInteger;
10+
import java.util.Objects;
1011

1112
/**
1213
* Sparse Merkle tree implementation.
@@ -30,14 +31,25 @@ public SparseMerkleTree(HashAlgorithm hashAlgorithm) {
3031
/**
3132
* Add leaf to the tree at given path.
3233
*
33-
* @param key path of the leaf
34-
* @param data data of the leaf
34+
* @param key path of the leaf; must be a 32-byte key
35+
* @param data data of the leaf; must be 32 bytes
3536
* @throws BranchExistsException if branch already exists at the path
3637
* @throws LeafOutOfBoundsException if leaf is out of bounds
37-
* @throws IllegalArgumentException if path is less than 1
38+
* @throws IllegalArgumentException if the key or data is not 32 bytes, or the path is less than 1
3839
*/
3940
public synchronized void addLeaf(byte[] key, byte[] data)
4041
throws BranchExistsException, LeafOutOfBoundsException {
42+
Objects.requireNonNull(key, "key cannot be null");
43+
Objects.requireNonNull(data, "data cannot be null");
44+
45+
if (key.length != 32) {
46+
throw new IllegalArgumentException("Key must be 32 bytes long.");
47+
}
48+
49+
if (data.length != 32) {
50+
throw new IllegalArgumentException("Data must be 32 bytes long.");
51+
}
52+
4153
BigInteger path = BitString.fromBytesReversedLSB(key).toBigInteger();
4254

4355
if (path.compareTo(BigInteger.ONE) <= 0) {
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package org.unicitylabs.sdk.smt.radix;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
import org.unicitylabs.sdk.crypto.hash.HashAlgorithm;
6+
7+
public class SparseMerkleTreeTest {
8+
9+
@Test
10+
void addLeafRejectsNon32ByteKeyOrData() {
11+
SparseMerkleTree tree = new SparseMerkleTree(HashAlgorithm.SHA256);
12+
Assertions.assertThrows(IllegalArgumentException.class,
13+
() -> tree.addLeaf(new byte[31], new byte[32]));
14+
Assertions.assertThrows(IllegalArgumentException.class,
15+
() -> tree.addLeaf(new byte[32], new byte[31]));
16+
Assertions.assertThrows(NullPointerException.class,
17+
() -> tree.addLeaf(null, new byte[32]));
18+
}
19+
}

0 commit comments

Comments
 (0)