comparison src/bitcaviar_plus/search.py @ 28:30535f42d0ff

refactor code
author Dennis Concepcion Martin <dennisconcepcionmartin@gmail.com>
date Wed, 02 Feb 2022 21:16:10 +0100
parents 32061555853c
children
comparison
equal deleted inserted replaced
27:348a07008703 28:30535f42d0ff
1
2 """ 1 """
3 Search methods for LEVELDB database 2 Search methods for LEVELDB database
4 """ 3 """
4
5 try:
6 # noinspection PyUnresolvedReferences
7 import plyvel
8 except ImportError:
9 # Avoid import error running unit tests
10 print("Couldn't import plyvel package. Are you running unit tests?")
11
12 import tempfile
13
14
15 def search_block_with(block_hash):
16 """
17 Search block with a given hash and get value
18 :param block_hash: string, required
19 :return: string
20 """
21
22 db = level_db_connect()
23 search_type = bytes.fromhex('62') # 'b' (block) in hex is 62
24 block_hash = bytes.fromhex(block_hash)[::-1]
25 key = search_type + block_hash
26 value = db.get(key)
27 db.close()
28
29 return value.hex()
30
31
32 # ---- SECONDARY METHODS ----
33
34 def deserialize_block_search(f):
35 """
36 Deserialize value (block search)
37 More info: https://bitcoin.stackexchange.com/questions/67515/format-of-a-block-keys-contents-in-bitcoinds-leveldb
38 :param f: buffer, required
39 :return: dict
40 """
41
42 client_number = f.read(3)
43 print('Client number: {}'.format(client_number.hex()))
44 block_height = f.read(1) # Var int 128?
45 print('Block height: {}'.format(block_height.hex()))
46 status = f.read(1) # var int 128?
47 print('Status: {}'.format(status.hex()))
48 number_of_transactions = f.read(1) # var int 128?
49 print('Number of transactions: {}'.format(number_of_transactions.hex()))
50
51
52 def create_file_with(binary):
53 with tempfile.TemporaryFile() as fp:
54 fp.write(binary)
55 fp.seek(0)
56
57 return fp
58
59
60 # noinspection PyUnresolvedReferences
61 def level_db_connect():
62 db = plyvel.DB('/bitcoin-node/.bitcoin/blocks/index/', create_if_missing=False)
63
64 return db
65
66
67 def get_128_var_int(f):
68 """
69 This var int is different from helpers.get_var_int
70 :param f:
71 :return: string
72 """
73
74 pass