From 3035876839082c9dca382b7c8ee80976f6889647 Mon Sep 17 00:00:00 2001 From: Brett Johnson Date: Wed, 18 Apr 2018 12:55:23 -0400 Subject: [PATCH] Error appropriately when putting invalid typed value in DHT (#48) * Fixes #46 * Remove some ambiguity in the way IStorage works in comment * Make documentation addition more clear * Remove unneeded line * Remove documentation example --- .gitignore | 2 +- kademlia/network.py | 21 +++++++++++++++++++++ kademlia/storage.py | 1 + 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a518055..c028402 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,4 @@ apidoc build dist kademlia.egg-info -docs/_build \ No newline at end of file +docs/_build diff --git a/kademlia/network.py b/kademlia/network.py index 372374c..ca87d3e 100644 --- a/kademlia/network.py +++ b/kademlia/network.py @@ -157,6 +157,10 @@ class Server(object): """ Set the given string key to the given value in the network. """ + if not check_dht_value_type(value): + raise TypeError( + "Value must be of type int, float, bool, str, or bytes" + ) log.info("setting '%s' = '%s' on network", key, value) dkey = digest(key) return await self.set_digest(dkey, value) @@ -235,3 +239,20 @@ class Server(object): self.saveStateRegularly, fname, frequency) + + +def check_dht_value_type(value): + """ + Checks to see if the type of the value is a valid type for + placing in the dht. + """ + typeset = set( + [ + int, + float, + bool, + str, + bytes, + ] + ) + return type(value) in typeset diff --git a/kademlia/storage.py b/kademlia/storage.py index 4e5dd64..71865f2 100644 --- a/kademlia/storage.py +++ b/kademlia/storage.py @@ -7,6 +7,7 @@ from collections import OrderedDict class IStorage: """ Local storage for this node. + IStorage implementations of get must return the same type as put in by set """ def __setitem__(self, key, value):