-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathrpc2.py
256 lines (206 loc) · 8.91 KB
/
rpc2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import bitcoinrpc.authproxy
import datetime
import gevent.queue
import os
import time
import base64
from collections import namedtuple
class RPCRequest(object):
def __init__(self, method, *params):
self.method = method
self.params = params
self.uuid = new_uuid()
self.timestamp = datetime.datetime.utcnow()
class RPCResponse(object):
def __init__(self, req, result, error=False):
self.req = req
self.result = result
self.error = error
self.timestamp = datetime.datetime.utcnow()
def new_uuid():
return base64.b64encode(os.urandom(16))
class BitcoinRPCClient(object):
def __init__(self, response_queue, block_store, rpcuser, rpcpassword, rpcip="localhost", rpcport=8332, protocol="http", testnet=False):
rpcurl = "{}://{}:{}@{}:{}".format(
protocol, rpcuser, rpcpassword, rpcip, rpcport)
self._handle = bitcoinrpc.authproxy.AuthServiceProxy(rpcurl, None, 500)
self._request_queue = gevent.queue.Queue()
self.connected = False
self._response_queue = response_queue # TODO: refactor this
self._block_store = block_store
self._disablewallet = False
def _call(self, req):
assert isinstance(req, RPCRequest)
# TODO: Does AuthServiceProxy have a time-out?
result = getattr(self._handle, req.method)(*req.params)
return RPCResponse(req, result)
def connect(self):
if self.connected:
return True # Assume it wasn't closed.
if not self._call(RPCRequest("getblockchaininfo")):
return False
try:
self._call(RPCRequest("getbalance"))
except bitcoinrpc.authproxy.JSONRPCException:
# wallet is probably disabled
self._disablewallet = True
self.connected = True
return True
def run(self):
assert self.connected
bestheight = None
bestblockhash = None
bestcoinbase = None
for req in self._request_queue:
resp = self._call(req) # TODO: exception handling
# TODO: enhackle
if req.method == "getnetworkhashps" or req.method == "estimatefee":
resp.result = {
"blocks": req.params[0],
"value": resp.result,
}
# Enhackerino
elif req.method == "getrawtransaction":
try:
tx = resp.result
tx['size'] = len(tx['hex'])/2
if 'coinbase' in tx['vin'][0]: # should always be at least 1 vin
tx['total_inputs'] = 'coinbase'
# This is pretty terrible
if req.params[0] == bestcoinbase:
coinbase_amount = 0
for output in resp.result['vout']:
if 'value' in output:
coinbase_amount += output['value']
resp2 = {"coinbase": coinbase_amount, "height": bestheight}
self._response_queue.put(resp2)
# TODO: Implement verbose mode
"""
if 'verbose' in s:
tx['total_inputs'] = 0
prev_tx = {}
for vin in tx['vin']:
if 'txid' in vin:
try:
txid = vin['txid']
if txid not in prev_tx:
prev_tx[txid] = rpcrequest(rpchandle, 'getrawtransaction', False,
txid, 1)
vin['prev_tx'] = prev_tx[txid]['vout'][vin['vout']]
if 'value' in vin['prev_tx']:
tx['total_inputs'] += vin['prev_tx']['value']
except:
pass
elif 'coinbase' in vin:
tx['total_inputs'] = 'coinbase'
for vout in tx['vout']:
try:
utxo = rpcrequest(rpchandle, 'gettxout', False,
s['txid'], vout['n'], False)
if utxo == None:
vout['spent'] = 'confirmed'
else:
utxo = rpcrequest(rpchandle, 'gettxout', False,
s['txid'], vout['n'], True)
if utxo == None:
vout['spent'] = 'unconfirmed'
else:
vout['spent'] = False
except:
pass
"""
except:
# TODO: Just use error in resp here
tx = {'txid': req.params[0], 'size': -1}
self._response_queue.put(tx)
continue
self._response_queue.put(resp)
if req.method == "getblockchaininfo":
new_bestblockhash = resp.result["bestblockhash"]
if new_bestblockhash != bestblockhash:
if not bestblockhash:
resp2 = {"lastblocktime" : 0}
else:
resp2 = {"lastblocktime" : time.time()}
bestheight = resp.result["blocks"]
bestblockhash = new_bestblockhash
# Request the new best block
self.request("getblock", bestblockhash)
# Request some other information
self.request("getnetworkhashps", 144)
self.request("getnetworkhashps", 2016)
self.request("estimatefee", 2)
self.request("estimatefee", 5)
self._response_queue.put(resp2)
elif req.method == "getblock" and req.params[0] == bestblockhash:
# Request the coinbase
bestcoinbase = resp.result["tx"][0]
self.request("getrawtransaction", bestcoinbase, 1)
elif req.method == "getblockhash":
self.request("getblock", resp.result)
if req.method == "getblock":
self._block_store.put_raw_block(resp.result)
# TODO: findblockbytimestamp
# TODO: consolecommand
# TODO: Remove for production
with open("test.log", "a") as f:
f.write("{} RESP {}{}\n".format(resp.timestamp, req.method, req.params))
def request(self, method, *params):
""" Asynchronous RPC request. """
if self._disablewallet and method in ["getbalance", "getunconfirmedbalance", "listsinceblock"]:
# Just lazy drop these.
return
req = RPCRequest(method, *params)
self._request_queue.put(req)
def sync_request(self, method, *params):
""" Synchronous RPC request. """
req = RPCRequest(method, *params)
return self._call(req)
def stop(self):
self._request_queue.put(StopIteration)
def testfn():
import config
cfg = config.read_file("bitcoin.conf")
rpcc = BitcoinRPCClient(
rpcuser=cfg["rpcuser"],
rpcpassword=cfg["rpcpassword"],
)
gevent.spawn(rpcc.run)
while True:
for i in range(10):
rpcc.request("getblockchaininfo")
print()
gevent.sleep(2)
print()
class Poller(object):
def __init__(self, rpcc):
self._rpcc = rpcc
self._mode = "monitor"
def run(self):
self.poll_once(force_all=True)
while True:
gevent.sleep(1)
self.poll_once()
def poll_once(self, force_all=False):
if self._mode == "monitor" or force_all:
self._rpcc.request("getconnectioncount")
self._rpcc.request("getmininginfo")
self._rpcc.request("getblockchaininfo")
self._rpcc.request("getbalance")
self._rpcc.request("getunconfirmedbalance")
if self._mode == "peers" or force_all:
self._rpcc.request("getconnectioncount")
self._rpcc.request("getpeerinfo")
if self._mode == "wallet" or force_all:
self._rpcc.request("listsinceblock")
self._rpcc.request("getbalance")
self._rpcc.request("getunconfirmedbalance")
if force_all:
self._rpcc.request("getchaintips")
# Net graph needs to run all the time.
self._rpcc.request("getnettotals")
def set_mode(self, mode):
# TODO: Add a lock here?
self._mode = mode
if __name__ == "__main__":
testfn()