changeset 3153:39bfd8cd4cd7 draft

RPCTypeCheck method to make type-checking JSON Arrays easier.
author Gavin Andresen <gavinandresen@gmail.com>
date Fri, 22 Jun 2012 18:36:42 -0400
parents bf716647e542
children 6c1eeeb7e4c2
files src/bitcoinrpc.cpp src/bitcoinrpc.h
diffstat 2 files changed, 52 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/bitcoinrpc.cpp
+++ b/src/bitcoinrpc.cpp
@@ -63,6 +63,43 @@
     return error;
 }
 
+void RPCTypeCheck(const Array& params,
+                  const list<Value_type>& typesExpected)
+{
+    int i = 0;
+    BOOST_FOREACH(Value_type t, typesExpected)
+    {
+        if (params.size() <= i)
+            break;
+
+       const Value& v = params[i];
+        if (v.type() != t)
+        {
+            string err = strprintf("Expected type %s, got %s",
+                                   Value_type_name[t], Value_type_name[v.type()]);
+            throw JSONRPCError(-3, err);
+        }
+        i++;
+    }
+}
+
+void RPCTypeCheck(const Object& o,
+                  const map<string, Value_type>& typesExpected)
+{
+    BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
+    {
+        const Value& v = find_value(o, t.first);
+        if (v.type() == null_type)
+            throw JSONRPCError(-3, strprintf("Missing %s", t.first.c_str()));
+        if (v.type() != t.second)
+        {
+            string err = strprintf("Expected type %s for %s, got %s",
+                                   Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
+            throw JSONRPCError(-3, err);
+        }
+    }
+}
+
 double GetDifficulty(const CBlockIndex* blockindex = NULL)
 {
     // Floating point number that is a multiple of the minimum difficulty,
--- a/src/bitcoinrpc.h
+++ b/src/bitcoinrpc.h
@@ -7,6 +7,7 @@
 #define _BITCOINRPC_H_ 1
 
 #include <string>
+#include <list>
 #include <map>
 
 #include "json/json_spirit_reader_template.h"
@@ -21,6 +22,20 @@
 /** Convert parameter values for RPC call from strings to command-specific JSON objects. */
 json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams);
 
+/*
+  Type-check arguments; throws JSONRPCError if wrong type given. Does not check that
+  the right number of arguments are passed, just that any passed are the correct type.
+  Use like:  RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type));
+*/
+void RPCTypeCheck(const json_spirit::Array& params,
+                  const std::list<json_spirit::Value_type>& typesExpected);
+/*
+  Check for expected keys/value types in an Object.
+  Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type));
+*/
+void RPCTypeCheck(const json_spirit::Object& o,
+                  const std::map<std::string, json_spirit::Value_type>& typesExpected);
+
 typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp);
 
 class CRPCCommand