def poloniex_query(): try: # bitfinex ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://api.bitfinex.com/v1//pubticker/btcusd'), timeout = 3).read()) btcprice = float(ret['mid']) except: try: # coinbase ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://coinbase.com/api/v1/prices/spot_rate?currency=USD'), timeout = 3).read()) btcprice = float(ret['amount']) except: try: # bitstamp ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://www.bitstamp.net/api/ticker/'), timeout = 3).read()) btcprice = float(ret['bid']) except: print 'unable to update price for BTC' sys.exit(1) try: # poloniex ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=returnTicker'),timeout=3).read())['BTC_NSR'] newpoloprice = btcprice * (float(ret['last']) + float(ret['highestBid']) + float(ret['lowestAsk']) + 0.5*float(ret['high24hr']) + 0.5*float(ret['low24hr']))/4 #ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=return24hVolume'),timeout=3).read())['BTC_NSR'] #polo_vol = ret['BTC'] except: print 'unable to update price for NSR' sys.exit(1) #try: #ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('http://data.bter.com/api/1/ticker/nsr_btc'),timeout=3).read()) #newbterprice = btcprice * (float(ret['last']) + float(ret['sell']) + float(ret['buy']) + 0.5*float(ret['high']) + 0.5*float(ret['low']))/4 #bter_vol = ret['vol_btc'] #except: # print 'unable to update price for NSR' # sys.exit(1) #newprice = newpoloprice * 0.75 + newbterprice * 0.25 #print polo_vol, bter_vol return newpoloprice
def test_handle_request_echo(self): handler = Handler(self.service) json = jsonrpc.dumps({'method':'echo', 'params':['foobar'], 'id':''}) expected = '{"result":"foobar", "id":"", "jsonrpc":"2.0"}' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads(expected))
def test_handle_request_echo(self): handler = Handler(self.service) json = jsonrpc.dumps({ 'method': 'echo', 'params': ['foobar'], 'id': '' }) expected = '{"result":"foobar", "id":"", "jsonrpc":"2.0"}' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads(expected))
def test_NestedDictAllTypes(self): json = jsonrpc.dumps({ 's': 'foobar', 'int': 1234, 'float': 1234.567, 'exp': 1234.56e78, 'negInt': -1234, 'None': None, 'True': True, 'False': False, 'list': [1, 2, 4, {}], 'dict': { 'a': 'b' } }) obj = jsonrpc.loads(json) self.assertEquals( obj, { 's': 'foobar', 'int': 1234, 'float': 1234.567, 'exp': 1234.56e78, 'negInt': -1234, 'None': None, 'True': True, 'False': False, 'list': [1, 2, 4, {}], 'dict': { 'a': 'b' } })
def test_translate_error(self): handler = Handler(self.service) exc = Exception() data = handler.translate_result('id', None, exc, None) self.assertEqual( jsonrpc.loads(data), {'id': 'id', 'error': {'code': -32603, 'message': ''}} )
def translate_bctx_to_bitcoindtx(tx_bc): tx = {} tx['locktime'] = 0 tx['txid'] = tx_bc['hash'] tx['version'] = tx_bc['ver'] tx['vin'] = [] tx['vout'] = [] for i in tx_bc['inputs']: v = {} v['scriptSig'] = {'asm': '', 'hex': ''} v['sequence'] = 4294967295 v['txid'] = jsonrpc.loads(urllib2.urlopen("http://blockchain.info/rawtx/%s" % (i['prev_out']['tx_index'],)).read())['hash'] v['vout'] = i['prev_out']['n'] tx['vin'].append(v) for i in range(len(tx_bc['out'])): o = tx_bc['out'][i] v = {} v['n'] = i v['scriptPubKey'] = {} v['scriptPubKey']['addresses'] = [o['addr']] v['scriptPubKey']['asm'] = [] v['scriptPubKey']['hex'] = [] v['scriptPubKey']['reqSigs'] = 1, v['scriptPubKey']['type'] = 'pubkeyhash' v['value'] = float(o['value'])/1e8 tx['vout'].append(v) return tx
def test_handle_request_BadRequestData(self): handler=Handler(self.service) json = 'This is not a JSON-RPC request' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': {'message': 'Parse error', 'code': -32700}, 'id': None})
def test_handle_request_BadRequestObject(self): handler=Handler(self.service) json = '{}' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': {'message': 'Invalid Request', 'code': -32600}, 'id': None})
def test_handle_request_BadRequestObject(self): handler = Handler(self.service) json = '{}' result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), {'error': {'message': 'Invalid Request', 'code': -32600}, 'id': None}, )
def test_handle_request_BadRequestData(self): handler = Handler(self.service) json = 'This is not a JSON-RPC request' result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), {'error': {'message': 'Parse error', 'code': -32700}, 'id': None}, )
def test_handle_request_MethodRaiseError(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'raise_error', 'params': [], 'id': ''}) result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), {'error': {'code': -32603, 'message': 'foobar'}, 'id': ''}, )
def test_translate_unencodable_results(self): handler = Handler(self.service) data = handler.translate_result('id', self, None, None) error = { 'message': 'Internal JSON-RPC error', 'code': -32603, } self.assertEquals(jsonrpc.loads(data), {'id': 'id', 'error': error})
def test_translate_results(self): handler = Handler(self.service) data = handler.translate_result('id', 'foobar', None, None) self.assertEquals(jsonrpc.loads(data), { 'jsonrpc': '2.0', 'result': 'foobar', 'id': 'id' })
def test_NestedDictAllTypes(self): json = jsonrpc.dumps({'s':'foobar', 'int':1234, 'float':1234.567, 'exp':1234.56e78, 'negInt':-1234, 'None':None,'True':True, 'False':False, 'list':[1,2,4,{}], 'dict':{'a':'b'}}) obj = jsonrpc.loads(json) self.assertEquals(obj, {'s':'foobar', 'int':1234, 'float':1234.567, 'exp':1234.56e78, 'negInt':-1234, 'None':None,'True':True, 'False':False, 'list':[1,2,4,{}], 'dict':{'a':'b'}})
def test_translate_error(self): handler=Handler(self.service) exc = Exception() data = handler.translate_result('id', None, exc, None) self.assertEquals(jsonrpc.loads(data), {'id':'id', 'error':{'code': -32603, 'message': ''}})
def btce_usd_query(): try: # btce ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://btc-e.com/api/2/ppc_usd/ticker'),timeout=3).read())['ticker'] price = ret['last'] volume = ret['vol'] except: print 'unable to update price for PPC on BTC-e (USD)' return 0,0 return price,volume
def test_handle_request_MethodNotFound(self): handler=Handler(self.service) json=jsonrpc.dumps({'method': 'not_found', 'params': ['foobar'], 'id':''}) result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': { 'message':'Method not found: not_found', 'code': -32601}, 'id':''})
def getaddresstxs(address): # Get all transactions associated with an address. # Uses blockchain.info to get this, bitcoind API # apparently has no equivalent function. address_url="http://blockchain.info/address/"+address+"?format=json" address_info = jsonrpc.loads(urllib2.urlopen(address_url).read()) tx_list = [] for tx in address_info['txs']: tx_list.append(tx['hash']) return tx_list
def test_handle_request_MethodRaiseError(self): handler=Handler(self.service) json=jsonrpc.dumps({'method': 'raise_error', 'params': [], 'id': ''}) result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': {'code': -32603, 'message': 'foobar'}, 'id':''})
def test_handle_request_MethodNotFound(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'not_found', 'params': ['foobar'], 'id': ''}) result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), { 'error': {'message': 'Method not found: not_found', 'code': -32601}, 'id': '', }, )
def gettx(txid): # Get the information of a single transaction, using # the bitcoind API try: tx_raw = sp.getrawtransaction(txid) tx = sp.decoderawtransaction(tx_raw) except: print "Error getting transaction "+txid+" details from bitcoind, trying blockchain.info" print "http://blockchain.info/rawtx/%s" % (txid,) tx_bc = jsonrpc.loads(urllib2.urlopen("http://blockchain.info/rawtx/%s" % (txid,)).read()) tx = translate_bctx_to_bitcoindtx(tx_bc) return tx
def jubi_cny_query(): try: # yahoo ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json'), timeout = 3).read()) for res in ret['list']['resources']: if res['resource']['fields']['name'] == 'USD/CNY': cnyprice = float(res['resource']['fields']['price']) except: print("unable to update CNY price from yahoo") try: # coindesk ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://api.coindesk.com/v1/bpi/currentprice/CNY.json'), timeout = 3).read()) cnyprice = float(ret['bpi']['CNY']['rate']) / float(ret['bpi']['USD']['rate']) except: print("unable to update price for CNY") return 0,0 try: # jubi ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('http://www.jubi.com/api/v1/ticker/?coin=ppc',headers={'User-Agent': ''}),timeout=3).read()) price = float(ret['last'])/cnyprice volume = float(ret['vol'])/cnyprice except: print 'unable to update price for PPC on jubi' return 0,0 return price,volume
def test_runHandler(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup(__file__ , fin, fout) jsonrpc.handler(req) data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), {"result":"foobar", "error":None, "id":""})
def test_ServiceImplementationNotFound(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup("foobar" , fin, fout) rslt = jsonrpc.handler(req) self.assertEquals(rslt, "OK") data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), {u'id': '', u'result': None, u'error': {u'message': '', u'name': u'ServiceImplementaionNotFound'}} )
def btce_btc_query(): try: # bitfinex ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://api.bitfinex.com/v1//pubticker/btcusd'), timeout = 3).read()) btcprice = float(ret['last_price']) except: try: # coinbase ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://coinbase.com/api/v1/prices/spot_rate?currency=USD'), timeout = 3).read()) btcprice = float(ret['amount']) except: try: # bitstamp ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://www.bitstamp.net/api/ticker/'), timeout = 3).read()) btcprice = float(ret['last']) except: print 'unable to update price for BTC' return 0,0 try: # btce ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://btc-e.com/api/2/ppc_btc/ticker'),timeout=3).read())['ticker'] price = ret['last']*btcprice volume = ret['vol']*btcprice except: print 'unable to update price for PPC on BTC-e (BTC)' return 0,0 return price,volume
def poloniex_btc_query(): try: # bitfinex ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://api.bitfinex.com/v1//pubticker/btcusd'), timeout = 3).read()) btcprice = float(ret['last_price']) except: try: # coinbase ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://coinbase.com/api/v1/prices/spot_rate?currency=USD'), timeout = 3).read()) btcprice = float(ret['amount']) except: try: # bitstamp ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://www.bitstamp.net/api/ticker/'), timeout = 3).read()) btcprice = float(ret['last']) except: print 'unable to update price for BTC' return 0,0 try: # poloniex ret = jsonrpc.loads(urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=returnTicker'),timeout=3).read())['BTC_PPC'] price = float(ret['last'])*btcprice volume = float(ret['baseVolume'])*btcprice except: print 'unable to update price for PPC on poloniex' return 0,0 return price,volume
def test_mod_python_handler(self): json = '{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() req = ApacheRequestMockup(__file__ , fin, fout) jsonrpc.handler(req) data = fout.getvalue() expect = { 'result': 'foobar', 'jsonrpc': '2.0', 'id': '', } actual = jsonrpc.loads(data) self.assertEquals(expect, actual)
def test_datetime_objects_roundtrip(self): """Test that we can serialize and un-serialize datetimes datetime objects are converted to strings when serializing, but we do not convert back to datetime. """ now = datetime.datetime.now() obj = {'time': now} value = jsonrpc.dumps(obj) unserialized = jsonrpc.loads(value) self.assertTrue(isinstance(unserialized['time'], ustr)) self.assertEqual(unserialized['time'], now.isoformat())
def test_mod_python_handler(self): json = b'{"method":"echo","params":["foobar"], "id":""}' fin = BytesIO(json) fout = BytesIO() req = ApacheRequestMockup(__file__, fin, fout) jsonrpc.handler(req) data = fout.getvalue() expect = { 'result': 'foobar', 'jsonrpc': '2.0', 'id': '', } actual = jsonrpc.loads(data) self.assertEqual(expect, actual)
def test_datetime_objects_roundtrip(self): """Test that we can serialize and un-serialize datetimes datetime objects are converted to strings when serializing, but we do not convert back to datetime. """ now = datetime.datetime.now() obj = {'time': now} value = jsonrpc.dumps(obj) unserialized = jsonrpc.loads(value) self.assertTrue(isinstance(unserialized['time'], basestring)) self.assertEqual(unserialized['time'], now.isoformat())
def test_runCGIHandler(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() env = {"CONTENT_LENGTH":len(json)} jsonrpc.handleCGI(service=Service(), fin=fin, fout=fout, env=env) data = StringIO(fout.getvalue()) data.readline() data.readline() data = data.read() self.assertEquals(jsonrpc.loads(data), {"result":"foobar", "error":None, "id":""})
def test_handleCGI(self): json = b'{"method":"echo","params":["foobar"], "id":""}' fin = BytesIO(json) fout = BytesIO() env = {'CONTENT_LENGTH': len(json)} jsonrpc.handleCGI(service=Service(), fin=fin, fout=fout, env=env) data = BytesIO(fout.getvalue()) data.readline() data.readline() data = data.read() expect = {'result': 'foobar', 'jsonrpc': '2.0', 'id': ''} actual = jsonrpc.loads(data) self.assertEqual(expect, actual)
def test_mod_python_handler(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup(__file__ , fin, fout) jsonrpc.handler(req) data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), {'result': 'foobar', 'jsonrpc': '2.0', 'id': ''})
def test_service_implementation_not_found(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup('foobar', fin, fout) rslt = jsonrpc.handler(req) self.assertEquals(rslt, 'OK') data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), {u'id': '', u'error': { u'message': 'Method not found', u'code': -32601}})
def test_mod_python_handler(self): from StringIO import StringIO json = u'{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() req = ApacheRequestMockup(__file__, fin, fout) jsonrpc.handler(req) data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), { 'result': 'foobar', 'jsonrpc': '2.0', 'id': '' })
def test_runHandler(self): from StringIO import StringIO json = u'{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() req = ApacheRequestMockup(__file__, fin, fout) jsonrpc.handler(req) data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), { "result": "foobar", "error": None, "id": "" })
def test_service_implementation_not_found(self): json = b'{"method":"echo","params":["foobar"], "id":""}' fin = BytesIO(json) fout = BytesIO() req = ApacheRequestMockup('foobar', fin, fout) rslt = jsonrpc.handler(req) self.assertEqual(rslt, 'OK') data = fout.getvalue() expect = { 'id': '', 'error': { 'message': 'Method not found', 'code': -32601 } } actual = jsonrpc.loads(data) self.assertEqual(expect, actual)
def test_service_implementation_not_found(self): from StringIO import StringIO json = u'{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() req = ApacheRequestMockup('foobar', fin, fout) rslt = jsonrpc.handler(req) self.assertEquals(rslt, 'OK') data = fout.getvalue() self.assertEquals(jsonrpc.loads(data), { u'id': '', u'error': { u'message': 'Method not found', u'code': -32601 } })
def test_handleCGI(self): from StringIO import StringIO json = '{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() env = {'CONTENT_LENGTH': len(json)} jsonrpc.handleCGI(service=Service(), fin=fin, fout=fout, env=env) data = StringIO(fout.getvalue()) data.readline() data.readline() data = data.read() self.assertEquals(jsonrpc.loads(data), {'result':'foobar', 'jsonrpc': '2.0', 'id':''})
def test_handleCGI(self): from StringIO import StringIO json=u'{"method":"echo","params":["foobar"], "id":""}' fin=StringIO(json) fout=StringIO() env = {'CONTENT_LENGTH': len(json)} jsonrpc.handleCGI(service=Service(), fin=fin, fout=fout, env=env) data = StringIO(fout.getvalue()) data.readline() data.readline() data = data.read() self.assertEquals(jsonrpc.loads(data), {'result':'foobar', 'jsonrpc': '2.0', 'id':''})
def test_runCGIHandler(self): from StringIO import StringIO json = u'{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() env = {"CONTENT_LENGTH": len(json)} jsonrpc.handleCGI(service=Service(), fin=fin, fout=fout, env=env) data = StringIO(fout.getvalue()) data.readline() data.readline() data = data.read() self.assertEquals(jsonrpc.loads(data), { "result": "foobar", "error": None, "id": "" })
def test_service_echoes_unicode(self): echo_data = {'hello': uchr(0x1234)} json = jsonrpc.dumps({ 'id': '', 'params': [echo_data], 'method': 'echo' }) fin = BytesIO(encode(json)) fout = BytesIO() req = ApacheRequestMockup(__file__, fin, fout) result = jsonrpc.handler(req) self.assertEqual(result, 'OK') data = fout.getvalue() expect = echo_data actual = jsonrpc.loads(data)['result'] self.assertEqual(expect, actual)
def test_service_echoes_unicode(self): echo_data = {'hello': unichr(0x1234)} json = jsonrpc.dumps({ 'id': '', 'params': [echo_data], 'method': 'echo', }) fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup(__file__, fin, fout) result = jsonrpc.handler(req) self.assertEquals(result, 'OK') data = fout.getvalue() expect = echo_data actual = jsonrpc.loads(data)['result'] self.assertEqual(expect, actual)
def test_ServiceImplementationNotFound(self): from StringIO import StringIO json = u'{"method":"echo","params":["foobar"], "id":""}' fin = StringIO(json) fout = StringIO() req = ApacheRequestMockup("foobar", fin, fout) rslt = jsonrpc.handler(req) self.assertEquals(rslt, "OK") data = fout.getvalue() self.assertEquals( jsonrpc.loads(data), { u'id': '', u'result': None, u'error': { u'message': '', u'name': u'ServiceImplementaionNotFound' } })
def test_translateUnencodableResults(self): handler=Handler(self.service) data=handler.translateResult(self, None, "spam") self.assertEquals(jsonrpc.loads(data), {"result":None,"id":"spam","error":{"name":"JSONEncodeException", "message":"Result Object Not Serializable"}})
def translate_request(self, data): try: return loads(data) except: raise ParseError(data)
def test_handleRequestMethodNotAllowed(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"not_a_ServiceMethod", 'params':['foobar'], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"ServiceMethodNotFound", "message":""}, "id":""})
def test_handleRequestMethodRaiseError(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"raiseError", 'params':[], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"Exception", "message":"foobar"}, "id":""})
def test_handleBadRequestData(self): handler=Handler(self.service) json = "This is not a JSON-RPC request" result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"ServiceRequestNotTranslatable", "message":json}, "id":""})
def test_handleBadRequestObject(self): handler=Handler(self.service) json = "{}" result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"BadServiceRequest", "message":json}, "id":""})
def test_translateError(self): handler=Handler(self.service) exc = Exception() data=handler.translateResult(None, exc, "id") self.assertEquals(jsonrpc.loads(data), {"result":None,"id":"id","error":{"name":"Exception", "message":""}})
def test_translate_results(self): handler = Handler(self.service) data = handler.translate_result('id', 'foobar', None, None) self.assertEquals(jsonrpc.loads(data), {'jsonrpc': '2.0', 'result': 'foobar', 'id': 'id'})
def translate_request(self, data): try: return loads(data) except (ValueError, Exception): raise ParseError(data)
def test_handleRequestEcho(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"echo", 'params':['foobar'], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads('{"result":"foobar", "error":null, "id":""}'))
def translateRequest(self, data): try: req = loads(data) except: raise ServiceRequestNotTranslatable(data) return req
def test_translateResults(self): handler=Handler(self.service) data=handler.translateResult("foobar", None, "spam") self.assertEquals(jsonrpc.loads(data), {"result":"foobar","id":"spam","error":None})