Skip to content

Commit c7913e0

Browse files
committed
Add safeGet feature for nonexistent key-value pair
1 parent e0cea79 commit c7913e0

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

contracts/implementation.sol

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,14 @@ contract PatriciaTreeImplementation {
1414
return tree.get(key);
1515
}
1616

17+
function safeGet(bytes key) public view returns (bytes) {
18+
return tree.safeGet(key);
19+
}
20+
21+
function doesInclude(bytes key) public view returns (bool) {
22+
return tree.doesInclude(key);
23+
}
24+
1725
function getValue(bytes32 hash) public view returns (bytes) {
1826
return tree.values[hash];
1927
}

contracts/tree.sol

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@ library PatriciaTree {
2525
return getValue(tree, _findNode(tree, key));
2626
}
2727

28+
function safeGet(Tree storage tree, bytes key) internal view returns (bytes value) {
29+
bytes32 valueHash = _findNode(tree, key);
30+
require(valueHash != bytes32(0));
31+
value = getValue(tree, valueHash);
32+
require(valueHash == keccak256(value));
33+
}
34+
35+
function doesInclude(Tree storage tree, bytes key) internal view returns (bool) {
36+
bytes32 valueHash = _findNode(tree, key);
37+
return (valueHash != bytes32(0));
38+
}
39+
2840
function getValue(Tree storage tree, bytes32 valueHash) internal view returns (bytes) {
2941
return tree.values[valueHash];
3042
}

test/PatriciaTree.test.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,5 +211,30 @@ contract('PatriciaTree', async ([_, primary, nonPrimary]) => {
211211
assert.equal(web3.toUtf8(await tree.get('foo')), 'bar')
212212
})
213213
})
214+
215+
describe('safeGet()', async () => {
216+
it('should return stored value for the given key', async () => {
217+
await tree.insert('foo', 'bar', { from: primary })
218+
assert.equal(web3.toUtf8(await tree.get('foo')), 'bar')
219+
})
220+
it('should throw if the given key is not included', async () => {
221+
await tree.insert('foo', 'bar', { from: primary })
222+
try {
223+
await tree.get('fuz')
224+
assert.fail('Did not reverted')
225+
} catch (e) {
226+
assert.ok('Reverted successfully')
227+
}
228+
})
229+
})
230+
231+
describe('doesInclude()', async () => {
232+
it('should return boolean whether the tree includes the given key or not', async () => {
233+
await tree.insert('foo', 'bar', { from: primary })
234+
assert.equal(await tree.doesInclude('foo'), true)
235+
assert.equal(await tree.doesInclude('fuz'), false)
236+
})
237+
})
238+
214239
})
215240
})

0 commit comments

Comments
 (0)