Skip to content

Commit d3fea9c

Browse files
committed
Refactor rpc BaseProxy
Reduce Amount of nesting when creating connection parameters
1 parent c86b9ac commit d3fea9c

File tree

2 files changed

+63
-22
lines changed

2 files changed

+63
-22
lines changed

bitcoin/rpc.py

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,36 @@ def default_btc_dir():
136136
return os.path.expanduser('~/.bitcoin')
137137

138138

139+
def parse_conf_file(file_object):
140+
conf = {}
141+
for line in file_object.readlines():
142+
if '#' in line:
143+
line = line[:line.index('#')]
144+
if '=' not in line:
145+
continue
146+
k, v = line.split('=', 1)
147+
conf[k.strip()] = v.strip()
148+
return conf
149+
150+
151+
def get_authpair(conf, network, btc_conf_file):
152+
cookie_dir = conf.get('datadir', os.path.dirname(btc_conf_file))
153+
if network != "mainnet":
154+
cookie_dir = os.path.join(cookie_dir, network)
155+
cookie_file = os.path.join(cookie_dir, ".cookie")
156+
157+
try:
158+
with open(cookie_file, 'r') as fd:
159+
return fd.read()
160+
except IOError as err:
161+
if 'rpcpassword' in conf:
162+
return "%s:%s" % (conf['rpcuser'], conf['rpcpassword'])
163+
164+
raise ValueError('Cookie file unusable (%s) and rpcpassword '
165+
'not specified in the configuration file: %r'
166+
% (err, btc_conf_file))
167+
168+
139169
class BaseProxy(object):
140170
"""Base JSON-RPC proxy class. Contains only private methods; do not use
141171
directly."""
@@ -164,14 +194,7 @@ def __init__(self,
164194
# Extract contents of bitcoin.conf to build service_url
165195
try:
166196
with open(btc_conf_file, 'r') as fd:
167-
for line in fd.readlines():
168-
if '#' in line:
169-
line = line[:line.index('#')]
170-
if '=' not in line:
171-
continue
172-
k, v = line.split('=', 1)
173-
conf[k.strip()] = v.strip()
174-
197+
conf.update(parse_conf_file(fd))
175198
# Treat a missing bitcoin.conf as though it were empty
176199
except FileNotFoundError:
177200
pass
@@ -184,19 +207,7 @@ def __init__(self,
184207
service_url = ('%s://%s:%d' %
185208
('http', conf['rpchost'], conf['rpcport']))
186209

187-
cookie_dir = conf.get('datadir', os.path.dirname(btc_conf_file))
188-
if bitcoin.params.NAME != "mainnet":
189-
cookie_dir = os.path.join(cookie_dir, bitcoin.params.NAME)
190-
cookie_file = os.path.join(cookie_dir, ".cookie")
191-
try:
192-
with open(cookie_file, 'r') as fd:
193-
authpair = fd.read()
194-
except IOError as err:
195-
if 'rpcpassword' in conf:
196-
authpair = "%s:%s" % (conf['rpcuser'], conf['rpcpassword'])
197-
198-
else:
199-
raise ValueError('Cookie file unusable (%s) and rpcpassword not specified in the configuration file: %r' % (err, btc_conf_file))
210+
authpair = get_authpair(conf, bitcoin.params.NAME, btc_conf_file)
200211

201212
else:
202213
url = urlparse.urlparse(service_url)

bitcoin/tests/test_rpc.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,38 @@
1111

1212

1313
import unittest
14+
import tempfile
15+
from bitcoin.rpc import Proxy, parse_conf_file, get_authpair
16+
17+
18+
class TestConfigFileparser(unittest.TestCase):
19+
def test_parse(self):
20+
with tempfile.TemporaryFile("w+") as fd:
21+
fd.write("""
22+
datadir = /home/user/.bitcoin
23+
# Comment
24+
dbcache = 300 # in MB # Inline comment
25+
""")
26+
fd.seek(0)
27+
self.assertEqual(parse_conf_file(fd), {
28+
"datadir": "/home/user/.bitcoin",
29+
"dbcache": "300"
30+
})
31+
32+
def test_authpair_from_conf(self):
33+
self.assertEqual(
34+
"user:insecure_youll_be_robed",
35+
get_authpair(
36+
{
37+
"rpcuser": "user",
38+
"rpcpassword": "insecure_youll_be_robed"
39+
}, "mainnet", "dummy.file"))
40+
41+
def test_authpair_fail(self):
42+
with self.assertRaises(ValueError):
43+
get_authpair({}, "testnet", "ou/conf")
44+
1445

15-
from bitcoin.rpc import Proxy
1646

1747
class Test_RPC(unittest.TestCase):
1848
# Tests disabled, see discussion below.

0 commit comments

Comments
 (0)