Skip to content

Commit ad40578

Browse files
committed
Refactor rpc BaseProxy
Reduce Amount of nesting when creating connection parameters
1 parent 39a3133 commit ad40578

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
@@ -123,6 +123,36 @@ def default_btc_dir():
123123
return os.path.expanduser('~/.bitcoin')
124124

125125

126+
def parse_conf_file(file_object):
127+
conf = {}
128+
for line in file_object.readlines():
129+
if '#' in line:
130+
line = line[:line.index('#')]
131+
if '=' not in line:
132+
continue
133+
k, v = line.split('=', 1)
134+
conf[k.strip()] = v.strip()
135+
return conf
136+
137+
138+
def get_authpair(conf, network, btc_conf_file):
139+
cookie_dir = conf.get('datadir', os.path.dirname(btc_conf_file))
140+
if network != "mainnet":
141+
cookie_dir = os.path.join(cookie_dir, network)
142+
cookie_file = os.path.join(cookie_dir, ".cookie")
143+
144+
try:
145+
with open(cookie_file, 'r') as fd:
146+
return fd.read()
147+
except IOError as err:
148+
if 'rpcpassword' in conf:
149+
return "%s:%s" % (conf['rpcuser'], conf['rpcpassword'])
150+
151+
raise ValueError('Cookie file unusable (%s) and rpcpassword '
152+
'not specified in the configuration file: %r'
153+
% (err, btc_conf_file))
154+
155+
126156
class BaseProxy(object):
127157
"""Base JSON-RPC proxy class. Contains only private methods; do not use
128158
directly."""
@@ -151,14 +181,7 @@ def __init__(self,
151181
# Extract contents of bitcoin.conf to build service_url
152182
try:
153183
with open(btc_conf_file, 'r') as fd:
154-
for line in fd.readlines():
155-
if '#' in line:
156-
line = line[:line.index('#')]
157-
if '=' not in line:
158-
continue
159-
k, v = line.split('=', 1)
160-
conf[k.strip()] = v.strip()
161-
184+
conf.update(parse_conf_file(fd))
162185
# Treat a missing bitcoin.conf as though it were empty
163186
except FileNotFoundError:
164187
pass
@@ -171,19 +194,7 @@ def __init__(self,
171194
service_url = ('%s://%s:%d' %
172195
('http', conf['rpchost'], conf['rpcport']))
173196

174-
cookie_dir = conf.get('datadir', os.path.dirname(btc_conf_file))
175-
if bitcoin.params.NAME != "mainnet":
176-
cookie_dir = os.path.join(cookie_dir, bitcoin.params.NAME)
177-
cookie_file = os.path.join(cookie_dir, ".cookie")
178-
try:
179-
with open(cookie_file, 'r') as fd:
180-
authpair = fd.read()
181-
except IOError as err:
182-
if 'rpcpassword' in conf:
183-
authpair = "%s:%s" % (conf['rpcuser'], conf['rpcpassword'])
184-
185-
else:
186-
raise ValueError('Cookie file unusable (%s) and rpcpassword not specified in the configuration file: %r' % (err, btc_conf_file))
197+
authpair = get_authpair(conf, bitcoin.params.NAME, btc_conf_file)
187198

188199
else:
189200
url = urlparse.urlparse(service_url)

bitcoin/tests/test_rpc.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,38 @@
1212
from __future__ import absolute_import, division, print_function, unicode_literals
1313

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

16-
from bitcoin.rpc import Proxy
1747

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

0 commit comments

Comments
 (0)