Skip to content

Commit 70c0b9f

Browse files
committed
Merge w/ feature/safe-get
1 parent 85b7a88 commit 70c0b9f

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

Diff for: contracts/implementation.sol

+8
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ contract PartialMerkleTreeImplementation {
2929
return tree.get(key);
3030
}
3131

32+
function safeGet(bytes key) public view returns (bytes) {
33+
return tree.safeGet(key);
34+
}
35+
36+
function doesInclude(bytes key) public view returns (bool) {
37+
return tree.doesInclude(key);
38+
}
39+
3240
function getValue(bytes32 hash) public view returns (bytes) {
3341
return tree.values[hash];
3442
}

Diff for: contracts/tree.sol

+12
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,18 @@ library PartialMerkleTree {
138138
return getValue(tree, _findNode(tree, key));
139139
}
140140

141+
function safeGet(Tree storage tree, bytes key) internal view returns (bytes value) {
142+
bytes32 valueHash = _findNode(tree, key);
143+
require(valueHash != bytes32(0));
144+
value = getValue(tree, valueHash);
145+
require(valueHash == keccak256(value));
146+
}
147+
148+
function doesInclude(Tree storage tree, bytes key) internal view returns (bool) {
149+
bytes32 valueHash = _findNode(tree, key);
150+
return (valueHash != bytes32(0));
151+
}
152+
141153
function getValue(Tree storage tree, bytes32 valueHash) internal view returns (bytes) {
142154
return tree.values[valueHash];
143155
}

Diff for: test/PartialMerkleTree.Test.js

+24
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,30 @@ contract('PartialMerkleTree', async ([_, primary, nonPrimary]) => {
143143
})
144144
})
145145

146+
describe('safeGet()', async () => {
147+
it('should return stored value for the given key', async () => {
148+
await tree.insert('foo', 'bar', { from: primary })
149+
assert.equal(web3.toUtf8(await tree.get('foo')), 'bar')
150+
})
151+
it('should throw if the given key is not included', async () => {
152+
await tree.insert('foo', 'bar', { from: primary })
153+
try {
154+
await tree.get('fuz')
155+
assert.fail('Did not reverted')
156+
} catch (e) {
157+
assert.ok('Reverted successfully')
158+
}
159+
})
160+
})
161+
162+
describe('doesInclude()', async () => {
163+
it('should return boolean whether the tree includes the given key or not', async () => {
164+
await tree.insert('foo', 'bar', { from: primary })
165+
assert.equal(await tree.doesInclude('foo'), true)
166+
assert.equal(await tree.doesInclude('fuz'), false)
167+
})
168+
})
169+
146170
describe('getNonInclusionProof()', async () => {
147171
let items = { key1: 'value1', key2: 'value2', key3: 'value3' }
148172
it('should return proof data when the key does not exist', async () => {

0 commit comments

Comments
 (0)