1 import plyvel, ast, hashlib, traceback, os
2 from processor import print_log
7 Patricia tree for hashing unspents
12 KEYLENGTH = 20 + 32 + 4 #56
14 class Storage(object):
16 def __init__(self, config, shared, test_reorgs):
18 self.dbpath = config.get('leveldb', 'path_fulltree')
19 if not os.path.exists(self.dbpath):
21 self.pruning_limit = config.getint('leveldb', 'pruning_limit')
26 self.test_reorgs = test_reorgs
28 self.db_utxo = plyvel.DB(os.path.join(self.dbpath,'utxo'), create_if_missing=True, compression=None)
29 self.db_addr = plyvel.DB(os.path.join(self.dbpath,'addr'), create_if_missing=True, compression=None)
30 self.db_hist = plyvel.DB(os.path.join(self.dbpath,'hist'), create_if_missing=True, compression=None)
31 self.db_undo = plyvel.DB(os.path.join(self.dbpath,'undo'), create_if_missing=True, compression=None)
33 traceback.print_exc(file=sys.stdout)
36 self.db_version = 2 # increase this when database needs to be updated
38 self.last_hash, self.height, db_version = ast.literal_eval(self.db_undo.get('height'))
39 print_log("Database version", self.db_version)
40 print_log("Blockchain height", self.height)
42 #traceback.print_exc(file=sys.stdout)
43 print_log('initializing database')
45 self.last_hash = '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f'
46 db_version = self.db_version
51 if self.db_version != db_version:
52 print_log("Your database '%s' is deprecated. Please create a new database"%self.dbpath)
59 self.root_hash, v = self.get_node_hash('',d,None)
60 print_log("UTXO tree root hash:", self.root_hash.encode('hex'))
61 print_log("Coins in database:", v)
63 # convert between bitcoin addresses and 20 bytes keys used for storage.
64 def address_to_key(self, addr):
65 return bc_address_to_hash_160(addr)
67 def key_to_address(self, addr):
68 return hash_160_to_bc_address(addr)
71 def get_proof(self, addr):
72 key = self.address_to_key(addr)
73 i = self.db_utxo.iterator(start=key)
81 v = self.db_utxo.get(item)
82 out.append((item.encode('hex'), v.encode('hex')))
87 def get_balance(self, addr):
88 key = self.address_to_key(addr)
89 i = self.db_utxo.iterator(start=key)
91 if not k.startswith(key):
93 p = self.get_parent(k)
99 def listunspent(self, addr):
100 key = self.address_to_key(addr)
103 for k, v in self.db_utxo.iterator(start=key):
104 if not k.startswith(key):
106 if len(k) == KEYLENGTH:
107 txid = k[20:52].encode('hex')
108 txpos = hex_to_int(k[52:56])
109 h = hex_to_int(v[8:12])
110 v = hex_to_int(v[0:8])
111 out.append({'tx_hash': txid, 'tx_pos':txpos, 'height': h, 'value':v})
113 out.sort(key=lambda x:x['height'])
117 def get_history(self, addr):
120 o = self.listunspent(addr)
122 out.append((item['tx_hash'], item['height']))
124 h = self.db_hist.get(addr)
129 txi = item[0:32].encode('hex')
130 hi = hex_to_int(item[36:40])
131 txo = item[40:72].encode('hex')
132 ho = hex_to_int(item[76:80])
133 out.append((txi, hi))
134 out.append((txo, ho))
137 out.sort(key=lambda x:x[1])
142 return map(lambda x: {'tx_hash':x[0], 'height':x[1]}, out)
146 def get_address(self, txi):
147 addr = self.db_addr.get(txi)
148 return self.key_to_address(addr) if addr else None
151 def get_undo_info(self, height):
152 s = self.db_undo.get("undo_info_%d" % (height % 100))
153 if s is None: print_log("no undo info for ", height)
157 def write_undo_info(self, height, bitcoind_height, undo_info):
158 if height > bitcoind_height - 100 or self.test_reorgs:
159 self.db_undo.put("undo_info_%d" % (height % 100), repr(undo_info))
162 def common_prefix(self, word1, word2):
163 max_len = min(len(word1),len(word2))
164 for i in range(max_len):
165 if word2[i] != word1[i]:
170 return word1[0:index]
173 def put_node(self, key, d, batch=None):
177 if chr(i) in d.keys():
180 if h is None: h = chr(0)*32
181 vv = int_to_hex(v, 8).decode('hex')
183 assert len(item) == 40
186 k = "0x%0.64X" % k # 32 bytes
187 k = k[2:].decode('hex')
193 self.db_utxo.put(key, out)
196 def get_node(self, key):
198 s = self.db_utxo.get(key)
202 #print "get node", key.encode('hex'), len(key), s.encode('hex')
204 k = int(s[0:32].encode('hex'), 16)
210 value = hex_to_int(s[32:40])
211 d[chr(i)] = (_hash, value)
219 def add_address(self, target, value, height):
220 assert len(target) == KEYLENGTH
225 i = self.db_utxo.iterator()
229 items = self.get_node(key)
231 if word[0] in items.keys():
233 i.seek(key + word[0])
234 new_key, _ = i.next()
236 if target.startswith(new_key):
237 # add value to the child node
239 word = target[len(key):]
243 assert key not in path
246 # prune current node and add new node
247 prefix = self.common_prefix(new_key, target)
250 ## get hash and value of new_key from parent (if it's a leaf)
251 if len(new_key) == KEYLENGTH:
252 parent_key = self.get_parent(new_key)
253 parent = self.get_node(parent_key)
254 z = parent[ new_key[len(parent_key)] ]
255 self.put_node(prefix, { target[index]:(None,0), new_key[index]:z } )
257 # if it is not a leaf, update the hash of new_key because skip_string changed
258 h, v = self.get_node_hash(new_key, self.get_node(new_key), prefix)
259 self.put_node(prefix, { target[index]:(None,0), new_key[index]:(h,v) } )
262 self.parents[new_key] = prefix
267 items[ word[0] ] = (None,0)
268 self.put_node(key,items)
272 s = (int_to_hex(value, 8) + int_to_hex(height,4)).decode('hex')
273 self.db_utxo.put(target, s)
274 # the hash of a node is the txid
275 _hash = target[20:52]
276 self.update_node_hash(target, path, _hash, value)
279 def update_node_hash(self, node, path, _hash, value):
285 self.hash_list[node] = (_hash, value)
288 def update_hashes(self):
290 nodes = {} # nodes to write
292 for i in range(KEYLENGTH, -1, -1):
294 for node in self.hash_list.keys():
295 if len(node) != i: continue
297 node_hash, node_value = self.hash_list.pop(node)
299 # for each node, compute its hash, send it to the parent
301 self.root_hash = node_hash
302 self.root_value = node_value
305 parent = self.parents[node]
307 # read parent.. do this in add_address
308 d = nodes.get(parent)
310 d = self.get_node(parent)
313 letter = node[len(parent)]
314 assert letter in d.keys()
316 if i != KEYLENGTH and node_hash is None:
317 d2 = self.get_node(node)
318 node_hash, node_value = self.get_node_hash(node, d2, parent)
320 assert node_hash is not None
322 d[letter] = (node_hash, node_value)
326 grandparent = self.parents[parent] if parent != '' else None
327 parent_hash, parent_value = self.get_node_hash(parent, d, grandparent)
328 self.hash_list[parent] = (parent_hash, parent_value)
331 # batch write modified nodes
332 batch = self.db_utxo.write_batch()
333 for k, v in nodes.items():
334 self.put_node(k, v, batch)
338 assert self.hash_list == {}
342 def get_node_hash(self, x, d, parent):
346 skip_string = x[len(parent)+1:]
350 d2 = sorted(d.items())
351 values = map(lambda x: x[1][1], d2)
352 hashes = map(lambda x: x[1][0], d2)
353 value = sum( values )
354 _hash = self.hash( skip_string + ''.join(hashes) )
358 def get_path(self, target):
362 i = self.db_utxo.iterator(start='')
366 i.seek(key + word[0])
368 new_key, _ = i.next()
369 is_child = new_key.startswith(key + word[0])
370 except StopIteration:
375 if target.startswith(new_key):
376 # add value to the child node
378 word = target[len(key):]
382 assert key not in path
385 print_log('not in tree', self.db_utxo.get(key+word[0]), new_key.encode('hex'))
394 def delete_address(self, leaf):
395 path = self.get_path(leaf)
397 print_log("addr not in tree", leaf.encode('hex'), self.key_to_address(leaf[0:20]), self.db_utxo.get(leaf))
400 s = self.db_utxo.get(leaf)
402 self.db_utxo.delete(leaf)
403 if leaf in self.hash_list:
404 self.hash_list.pop(leaf)
407 letter = leaf[len(parent)]
408 items = self.get_node(parent)
411 # remove key if it has a single child
413 letter, v = items.items()[0]
415 self.db_utxo.delete(parent)
416 if parent in self.hash_list:
417 self.hash_list.pop(parent)
419 # we need the exact length for the iteration
420 i = self.db_utxo.iterator()
421 i.seek(parent+letter)
424 # note: k is not necessarily a leaf
425 if len(k) == KEYLENGTH:
426 _hash, value = k[20:52], hex_to_int(v[0:8])
428 _hash, value = None, None
430 self.update_node_hash(k, path[:-1], _hash, value)
433 self.put_node(parent, items)
434 _hash, value = None, None
435 self.update_node_hash(parent, path[:-1], _hash, value)
440 def get_children(self, x):
441 i = self.db_utxo.iterator()
446 if k.startswith(x+chr(l)):
449 elif k.startswith(x):
451 l = ord(k[len(x)]) + 1
458 def get_parent(self, x):
459 """ return parent and skip string"""
460 i = self.db_utxo.iterator()
461 for j in range(len(x)):
465 if x.startswith(k) and x!=k:
472 if DEBUG: return "hash("+x+")"
476 def get_root_hash(self):
477 return self.root_hash
487 def add_to_history(self, addr, tx_hash, tx_pos, value, tx_height):
488 key = self.address_to_key(addr)
489 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
491 # write the new history
492 self.add_address(key + txo, value, tx_height)
495 self.db_addr.put(txo, key)
499 def revert_add_to_history(self, addr, tx_hash, tx_pos, value, tx_height):
500 key = self.address_to_key(addr)
501 txo = (tx_hash + int_to_hex(tx_pos, 4)).decode('hex')
504 self.delete_address(key + txo)
507 self.db_addr.delete(txo)
511 def set_spent(self, addr, txi, txid, index, height, undo):
512 key = self.address_to_key(addr)
515 s = self.delete_address(leaf)
516 value = hex_to_int(s[0:8])
517 in_height = hex_to_int(s[8:12])
518 undo[leaf] = value, in_height
520 # delete backlink txi-> addr
521 self.db_addr.delete(txi)
524 s = self.db_hist.get(addr)
526 txo = (txid + int_to_hex(index,4) + int_to_hex(height,4)).decode('hex')
527 s += txi + int_to_hex(in_height,4).decode('hex') + txo
528 s = s[ -80*self.pruning_limit:]
529 self.db_hist.put(addr, s)
533 def revert_set_spent(self, addr, txi, undo):
534 key = self.address_to_key(addr)
538 self.db_addr.put(txi, key)
540 v, height = undo.pop(leaf)
541 self.add_address(leaf, v, height)
543 # revert add to history
544 s = self.db_hist.get(addr)
545 # s might be empty if pruning limit was reached
549 assert s[-80:-44] == txi
551 self.db_hist.put(addr, s)
558 def import_transaction(self, txid, tx, block_height, touched_addr):
560 undo = { 'prev_addr':[] } # contains the list of pruned items for each address in the tx; also, 'prev_addr' is a list of prev addresses
563 for i, x in enumerate(tx.get('inputs')):
564 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
565 addr = self.get_address(txi)
567 self.set_spent(addr, txi, txid, i, block_height, undo)
568 touched_addr.add(addr)
569 prev_addr.append(addr)
571 undo['prev_addr'] = prev_addr
573 # here I add only the outputs to history; maybe I want to add inputs too (that's in the other loop)
574 for x in tx.get('outputs'):
575 addr = x.get('address')
576 if addr is None: continue
577 self.add_to_history(addr, txid, x.get('index'), x.get('value'), block_height)
578 touched_addr.add(addr)
583 def revert_transaction(self, txid, tx, block_height, touched_addr, undo):
584 #print_log("revert tx", txid)
585 for x in reversed(tx.get('outputs')):
586 addr = x.get('address')
587 if addr is None: continue
588 self.revert_add_to_history(addr, txid, x.get('index'), x.get('value'), block_height)
589 touched_addr.add(addr)
591 prev_addr = undo.pop('prev_addr')
592 for i, x in reversed(list(enumerate(tx.get('inputs')))):
595 txi = (x.get('prevout_hash') + int_to_hex(x.get('prevout_n'), 4)).decode('hex')
596 self.revert_set_spent(addr, txi, undo)
597 touched_addr.add(addr)