restore old accounts from seed
[electrum-nvc.git] / lib / simple_config.py
1 import json, ast
2 import os, ast
3 from util import user_dir, print_error
4
5 from version import ELECTRUM_VERSION, SEED_VERSION
6
7
8
9 class SimpleConfig:
10     """
11 The SimpleConfig class is responsible for handling operations involving
12 configuration files.  The constructor reads and stores the system and 
13 user configurations from electrum.conf into separate dictionaries within
14 a SimpleConfig instance then reads the wallet file.
15 """
16     def __init__(self, options={}):
17
18         # system conf, readonly
19         self.system_config = {}
20         if options.get('portable') == False:
21             self.read_system_config()
22
23         # user conf, writeable
24         self.user_dir = user_dir()
25         self.user_config = {}
26         if options.get('portable') == False:
27             self.read_user_config()
28
29         # command-line options
30         self.options_config = options
31
32         self.wallet_config = {}
33         self.wallet_file_exists = False
34         self.init_path(self.options_config.get('wallet_path'))
35         print_error( "path", self.path )
36         if self.path:
37             self.read_wallet_config(self.path)
38
39         # portable wallet: use the same directory for wallet and headers file
40         if options.get('portable'):
41             self.wallet_config['blockchain_headers_path'] = os.path.dirname(self.path)
42             
43             
44         
45
46     def set_key(self, key, value, save = False):
47         # find where a setting comes from and save it there
48         if self.options_config.get(key) is not None:
49             print "Warning: not changing '%s' because it was passed as a command-line option"%key
50             return
51
52         elif self.user_config.get(key) is not None:
53             self.user_config[key] = value
54             if save: self.save_user_config()
55
56         elif self.system_config.get(key) is not None:
57             if str(self.system_config[key]) != str(value):
58                 print "Warning: not changing '%s' because it was set in the system configuration"%key
59
60         elif self.wallet_config.get(key) is not None:
61             self.wallet_config[key] = value
62             if save: self.save_wallet_config()
63
64         else:
65             # add key to wallet config
66             self.wallet_config[key] = value
67             if save: self.save_wallet_config()
68
69
70     def get(self, key, default=None):
71         """Retrieve the filepath of the configuration file specified in the 'key' parameter."""
72         # 1. command-line options always override everything
73         if self.options_config.has_key(key) and self.options_config.get(key) is not None:
74             out = self.options_config.get(key)
75
76         # 2. user configuration 
77         elif self.user_config.has_key(key):
78             out = self.user_config.get(key)
79
80         # 2. system configuration
81         elif self.system_config.has_key(key):
82             out = self.system_config.get(key)
83
84         # 3. use the wallet file config
85         else:
86             out = self.wallet_config.get(key)
87
88         if out is None and default is not None:
89             out = default
90
91         # try to fix the type
92         if default is not None and type(out) != type(default):
93             import ast
94             try:
95                 out = ast.literal_eval(out)
96             except:
97                 print "type error for '%s': using default value"%key
98                 out = default
99
100         return out
101
102
103     def is_modifiable(self, key):
104         """Check if the config file is modifiable."""
105         if self.options_config.has_key(key):
106             return False
107         elif self.user_config.has_key(key):
108             return True
109         elif self.system_config.has_key(key):
110             return False
111         else:
112             return True
113
114
115     def read_system_config(self):
116         """Parse and store the system config settings in electrum.conf into system_config[]."""
117         name = '/etc/electrum.conf'
118         if os.path.exists(name):
119             try:
120                 import ConfigParser
121             except ImportError:
122                 print "cannot parse electrum.conf. please install ConfigParser"
123                 return
124                 
125             p = ConfigParser.ConfigParser()
126             p.read(name)
127             try:
128                 for k, v in p.items('client'):
129                     self.system_config[k] = v
130             except ConfigParser.NoSectionError:
131                 pass
132
133
134     def read_user_config(self):
135         """Parse and store the user config settings in electrum.conf into user_config[]."""
136         if not self.user_dir: return
137
138         name = os.path.join( self.user_dir, 'electrum.conf')
139         if os.path.exists(name):
140             try:
141                 import ConfigParser
142             except ImportError:
143                 print "cannot parse electrum.conf. please install ConfigParser"
144                 return
145                 
146             p = ConfigParser.ConfigParser()
147             p.read(name)
148             try:
149                 for k, v in p.items('client'):
150                     self.user_config[k] = v
151             except ConfigParser.NoSectionError:
152                 pass
153
154     def init_path(self, path):
155         """Set the path of the wallet."""
156
157         if not path:
158             path = self.get('default_wallet_path')
159
160         if path is not None:
161             self.path = path
162             return
163
164         # Look for wallet file in the default data directory.
165         # Make wallet directory if it does not yet exist.
166         if not os.path.exists(self.user_dir):
167             os.mkdir(self.user_dir)
168         self.path = os.path.join(self.user_dir, "electrum.dat")
169
170
171     def save_user_config(self):
172         if not self.user_dir: return
173
174         import ConfigParser
175         config = ConfigParser.RawConfigParser()
176         config.add_section('client')
177         for k,v in self.user_config.items():
178             config.set('client', k, v)
179
180         with open( os.path.join( self.user_dir, 'electrum.conf'), 'wb') as configfile:
181             config.write(configfile)
182         
183
184
185
186     def read_wallet_config(self, path):
187         """Read the contents of the wallet file."""
188         try:
189             with open(self.path, "r") as f:
190                 data = f.read()
191         except IOError:
192             return
193         try:
194             d = ast.literal_eval( data )  #parse raw data from reading wallet file
195         except:
196             raise IOError("Cannot read wallet file.")
197
198         self.wallet_config = d
199         self.wallet_file_exists = True
200
201
202
203     def save(self, key=None):
204         self.save_wallet_config()
205
206
207     def save_wallet_config(self):
208         # prevent the creation of incomplete wallets  
209         #if self.wallet_config.get('master_public_keys') is None: 
210         #    return
211
212         s = repr(self.wallet_config)
213         f = open(self.path,"w")
214         f.write( s )
215         f.close()
216         if self.get('gui') != 'android':
217             import stat
218             os.chmod(self.path,stat.S_IREAD | stat.S_IWRITE)
219