Python

如何將帶有 getinfo 的 python 範例轉換為可用函式?

  • August 28, 2019

在 Antonopoulos 的書中,我嘗試使用第 49 頁上的範例 3-3,它使用了一個呼叫 python 腳本rpc_example.py來顯示 JSON-RPC API 的用法:

   from bitcoin.rpc import RawProxy
   p = RawProxy()
   info = p.getinfo()
   print(info['blocks'])

$ python rpc_example.py應該給哪個394875


當然getinfo已經被貶低了,我想使用另一個功能,例如getblock.

我不確定我是否正確使用它,或者我的語法是否有錯誤,或者下面的問題是否與 python 有關。


我已經在安裝庫時遇到了一些麻煩,pip install python-bitcoinlib並且也這樣做了,pip3 install python-bitcoinlib因為我不確定我現在遇到的問題是否與 python 版本 2 中的編碼/解碼有關。


我現在的程式碼是

from bitcoin.rpc import RawProxy
p = RawProxy()
infoblock = p.getblock()
print(infoblock['difficulty'])

這應該列印出塊的難度,至少在我的理解中(我是 python 和比特幣的新手)。

python 2出現以下錯誤:

$ python BuchSkripte/49_rpc_example.py
Traceback (most recent call last):
File "BuchSkripte/49_rpc_example.py", line 2, in <module>
   p = RawProxy()
File "/usr/local/lib/python2.7/dist-packages/bitcoin/rpc.py", line 295, in __init__
   **kwargs)
File "/usr/local/lib/python2.7/dist-packages/bitcoin/rpc.py", line 159, 
in __init__
   if '#' in line:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)

使用 python3 我得到:

$ python3 BuchSkripte/49_rpc_example.py
Traceback (most recent call last):
 File "BuchSkripte/49_rpc_example.py", line 3, in <module>
   infoblock = p.getblock()
 File "/usr/local/lib/python3.5/dist-packages/bitcoin/rpc.py", line 306, in <lambda>
   f = lambda *args: self._call(name, *args)
 File "/usr/local/lib/python3.5/dist-packages/bitcoin/rpc.py", line 238, in _call
   raise JSONRPCError(response['error'])
bitcoin.rpc.JSONRPCError: {'code': -1, 'message': 'getblock "blockhash" ( verbosity )\n\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block \'hash\'.\nIf verbosity is 1, returns an Object with information about block <hash>.\nIf verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n\nArguments:\n1. blockhash    (string, required) The block hash\n2. verbosity    (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n\nResult (for verbosity = 0):\n"data"             (string) A string that is serialized, hex-encoded data for block \'hash\'.\n\nResult (for verbosity = 1):\n{\n  "hash" : "hash",     (string) the block hash (same as provided)\n  "confirmations" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n  "size" : n,            (numeric) The block size\n  "strippedsize" : n,    (numeric) The block size excluding witness data\n  "weight" : n           (numeric) The block weight as defined in BIP 141\n  "height" : n,          (numeric) The block height or index\n  "version" : n,         (numeric) The block version\n  "versionHex" : "00000000", (string) The block version formatted in hexadecimal\n  "merkleroot" : "xxxx", (string) The merkle root\n  "tx" : [               (array of string) The transaction ids\n     "transactionid"     (string) The transaction id\n     ,...\n  ],\n  "time" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n  "mediantime" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n  "nonce" : n,           (numeric) The nonce\n  "bits" : "1d00ffff", (string) The bits\n  "difficulty" : x.xxx,  (numeric) The difficulty\n  "chainwork" : "xxxx",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n  "nTx" : n,             (numeric) The number of transactions in the block.\n  "previousblockhash" : "hash",  (string) The hash of the previous block\n  "nextblockhash" : "hash"       (string) The hash of the next block\n}\n\nResult (for verbosity = 2):\n{\n  ...,                     Same output as verbosity = 1.\n  "tx" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 "tx" result.\n         ,...\n  ],\n  ,...                     Same output as verbosity = 1.\n}\n\nExamples:\n> bitcoin-cli getblock "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"\n> curl --user myusername --data-binary \'{"jsonrpc": "1.0", "id":"curltest", "method": "getblock", "params": ["00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"] }\' -H \'content-type: text/plain;\' http://127.0.0.1:8332/\n'}

您的程式碼執行良好,但是當您呼叫函式 getBlock() 時出現錯誤,比特幣核心引用 getBlock() 函式有一個參數,此參數是塊的雜湊值。

因此,您的程式碼可以正常工作,因為 RPC 框架響應錯誤

bitcoin.rpc.JSONRPCError: {'code': -1, 'message': 'getblock "blockhash" ( verbosity )\n\nIf verbosity is 0, returns a string that is serialized, hex-encoded data for block \'hash\'.\nIf verbosity is 1, returns an Object with information about block <hash>.\nIf verbosity is 2, returns an Object with information about block <hash> and information about each transaction. \n\nArguments:\n1. blockhash    (string, required) The block hash\n2. verbosity    (numeric, optional, default=1) 0 for hex-encoded data, 1 for a json object, and 2 for json object with transaction data\n\nResult (for verbosity = 0):\n"data"             (string) A string that is serialized, hex-encoded data for block \'hash\'.\n\nResult (for verbosity = 1):\n{\n  "hash" : "hash",     (string) the block hash (same as provided)\n  "confirmations" : n,   (numeric) The number of confirmations, or -1 if the block is not on the main chain\n  "size" : n,            (numeric) The block size\n  "strippedsize" : n,    (numeric) The block size excluding witness data\n  "weight" : n           (numeric) The block weight as defined in BIP 141\n  "height" : n,          (numeric) The block height or index\n  "version" : n,         (numeric) The block version\n  "versionHex" : "00000000", (string) The block version formatted in hexadecimal\n  "merkleroot" : "xxxx", (string) The merkle root\n  "tx" : [               (array of string) The transaction ids\n     "transactionid"     (string) The transaction id\n     ,...\n  ],\n  "time" : ttt,          (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n  "mediantime" : ttt,    (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n  "nonce" : n,           (numeric) The nonce\n  "bits" : "1d00ffff", (string) The bits\n  "difficulty" : x.xxx,  (numeric) The difficulty\n  "chainwork" : "xxxx",  (string) Expected number of hashes required to produce the chain up to this block (in hex)\n  "nTx" : n,             (numeric) The number of transactions in the block.\n  "previousblockhash" : "hash",  (string) The hash of the previous block\n  "nextblockhash" : "hash"       (string) The hash of the next block\n}\n\nResult (for verbosity = 2):\n{\n  ...,                     Same output as verbosity = 1.\n  "tx" : [               (array of Objects) The transactions in the format of the getrawtransaction RPC. Different from verbosity = 1 "tx" result.\n         ,...\n  ],\n  ,...                     Same output as verbosity = 1.\n}\n\nExamples:\n> bitcoin-cli getblock "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"\n> curl --user myusername --data-binary \'{"jsonrpc": "1.0", "id":"curltest", "method": "getblock", "params": ["00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"] }\' -H \'content-type: text/plain;\' http://127.0.0.1:8332/\n'}

我認為問題在於你的配置 bitcoin-core,RawProxy 的程式碼,希望將比特幣配置在預設目錄中

這是如何配置庫的程式碼

if service_url is None:
           # Figure out the path to the bitcoin.conf file
           if btc_conf_file is None:
               if platform.system() == 'Darwin':
                   btc_conf_file = os.path.expanduser('~/Library/Application Support/Bitcoin/')
               elif platform.system() == 'Windows':
                   btc_conf_file = os.path.join(os.environ['APPDATA'], 'Bitcoin')
               else:
                   btc_conf_file = os.path.expanduser('~/.bitcoin')
               btc_conf_file = os.path.join(btc_conf_file, 'bitcoin.conf')

           # Bitcoin Core accepts empty rpcuser, not specified in btc_conf_file
           conf = {'rpcuser': ""}

           # Extract contents of bitcoin.conf to build service_url
           try:
               with open(btc_conf_file, 'r') as fd:
                   for line in fd.readlines():
                       if '#' in line:
                           line = line[:line.index('#')]
                       if '=' not in line:
                           continue
                       k, v = line.split('=', 1)
                       conf[k.strip()] = v.strip()

           # Treat a missing bitcoin.conf as though it were empty
           except FileNotFoundError:
               pass

           if service_port is None:
               service_port = bitcoin.params.RPC_PORT
           conf['rpcport'] = int(conf.get('rpcport', service_port))
           conf['rpchost'] = conf.get('rpcconnect', 'localhost')

           service_url = ('%s://%s:%d' %
               ('http', conf['rpchost'], conf['rpcport']))

在您的程式碼中,如果您使用正確的語法編寫,您可以使用塊的雜湊執行命令,一個範例

from bitcoin.rpc import RawProxy
p = RawProxy()
hash = p.getbestblockhash(0)
infoblock = p.getblock(hash)
print(infoblock['time'])

這是比特幣核心的官方文件rpc框架

引用自:https://bitcoin.stackexchange.com/questions/90058