2017-02-12 53 views
0

我一直在努力幾個小時,而我只是不知道自己在做錯什麼。它只是用於規劃/研究(不是性能) - 用github中的一些代碼來玩 - 但我需要看到它的功能。比特幣json rpc與python請求模塊?

RPC_USER = username 
RPC_PASS = pasword 
rpc_id = ID HERE 
jsonrpc = "2.0" 
payload = {"jsonrpc": jsonrpc, "id": rpc_id, "method": method, "params": params} 
authstr = base64.encodestring(bytes('%s:%s' % (RPC_USER, RPC_PASS), 'utf-8')).strip() 
request_headers = {"Authorization": "Basic %s" % authstr, 'content-type': 'application/json'} 
try: 
    response = requests.get(RPC_URL, headers = request_headers, data = json.dumps(payload)).json() 
    print(response['result'])  
except Exception as e: print(str(e)) 
if response['id'] != rpc_id: 
     raise ValueError("invalid response id!") 

我得到一個錯誤如下:

這裏是整個回溯:

Expecting value: line 1 column 1 (char 0)#將異常

Traceback (most recent call last): 
    File "miner_2017.py", line 411, in <module> 
    solo_miner(bin2hex("------coinbase message here -----"), "-----bitcoin address here-----") 
    File "miner_2017.py", line 401, in solo_miner 
    mined_block, hps = block_mine(rpc_getblocktemplate(), coinbase_message, 0, address, timeout=60) 
    File "miner_2017.py", line 63, in rpc_getblocktemplate 
    try: return rpc("getblocktemplate", [{}]) 
    File "miner_2017.py", line 52, in rpc 
    if response['id'] != rpc_id: 
UnboundLocalError: local variable 'response' referenced before assignment 

哪個後做一些看似乎是一個問題從字節對象而不是字符串對象解碼json對象。我不知道如何解決這個問題。由於json問題,似乎「響應」變量賦值失敗。如何從請求中獲取字符串形式的json對象?

有人能幫我嗎?由於

+0

類似的東西請出示完整的錯誤追蹤,而不僅僅是最後一行的一部分。 – jwodder

+0

增加了追蹤的其餘部分。 – Engine

回答

1
#!/usr/bin/env python 

import getpass 
import json 
import requests  

def instruct_wallet(method, params): 
    url = "http://127.0.0.1:8332/" 
    payload = json.dumps({"method": method, "params": params}) 
    headers = {'content-type': "application/json", 'cache-control': "no-cache"} 
    try: 
     response = requests.request("POST", url, data=payload, headers=headers, auth=(rpc_user, rpc_pass)) 
     return json.loads(response.text) 
    except requests.exceptions.RequestException as e: 
     print e 
    except: 
     print 'No response from Wallet, check Bitcoin is running on this machine' 

rpc_user='foo' 
rpc_password='bar' 
passphrase = getpass.getpass('Enter your wallet passphrase: ') 
timeout = raw_input('Unlock for how many seconds: ') 

answer = instruct_wallet('walletpassphrase', [passphrase, timeout]) 
if answer['error'] != None: 
    print answer['error'] 
else: 
    print answer['result'] 

我使用Altcoins