-
Notifications
You must be signed in to change notification settings - Fork 9
/
utxodump.py
178 lines (144 loc) · 4.51 KB
/
utxodump.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python
#
# Dump utxo data from the chainstate leveldb database in CSV output format.
# Dumps all fields except the script pub key.
import argparse
import binascii
import enum
import csv
import operator
import os
import sys
from collections import defaultdict
from typing import Tuple
import leveldb
class RowType(enum.Enum):
COIN = 'C'
COINS = 'c'
BLOCK_FILES = 'f'
TXINDEX = 't'
BLOCK_INDEX = 'b'
BEST_BLOCK = 'B'
HEAD_BLOCK = 'H'
FLAG = 'F'
REINDEX_FLAG = 'R'
LAST_BLOCK = 'l'
OBFUSCATE = '\x0e'
# Prefix for coins.
COIN = 67
# The obfuscation key.
OBFUSCATE_KEY = bytearray(b'\x0e\x00obfuscate_key')
def get_obfuscate_key(conn: leveldb.LevelDB) -> bytearray:
"""Load the obfuscation key from the database."""
secret = conn.Get(OBFUSCATE_KEY)
assert secret[0] == 8 and len(secret) == 9
return secret[1:]
def decrypt(ciphertext: bytearray, key: bytearray):
"""Decrypt data using an XOR cipher."""
for i, c in enumerate(ciphertext):
ciphertext[i] = c ^ key[i % len(key)]
def decode_varint(val: bytearray) -> Tuple[int, int]:
"""Decode a varint. Returns the value and number of bytes consumed."""
n = 0
for i, c in enumerate(val):
n = (n << 7) | (c & 0x7f)
if c & 0x80:
n += 1
else:
return n, i + 1
assert False # not reached
def decompress_amount(x: int) -> int:
"""Decompress an output amount."""
if x == 0:
return 0
x -= 1
e = x % 10
x //= 10
n = 0
if e < 9:
d = (x % 9) + 1
x //= 9
n = x * 10 + d
else:
n = x + 1
while e:
n *= 10
e -= 1
return n
def decode_key(key: bytearray) -> Tuple[str, int]:
"""Decode key to (txid, vout)."""
assert key[0] == COIN
txid = binascii.hexlify(key[1:33][::-1]).decode('utf8')
compressed_vout = key[33:]
vout, declen = decode_varint(compressed_vout)
assert declen == len(compressed_vout)
return txid, vout
def decode_val(val: bytearray) -> Tuple[int, int, int, int]:
"""Decode val to (height, coinbase, amount)."""
code, consumed = decode_varint(val)
coinbase = code & 1
height = code >> 1
txval, rem = decode_varint(val[consumed:])
return height, coinbase, decompress_amount(txval), len(val) - rem
def locate_db(testnet: bool, name: str) -> str:
"""Guess where the chainstate directory is."""
datadir = os.path.expanduser('~/.bitcoin')
if testnet:
datadir = os.path.join(datadir, 'testnet3')
return os.path.join(datadir, name)
def dump_chainstate_csv(conn: leveldb.LevelDB):
secret = get_obfuscate_key(conn)
writer = csv.writer(sys.stdout)
writer.writerow(
['txid', 'vout', 'height', 'coinbase', 'amount', 'scriptsize'])
for k, v in conn.RangeIter(b'C', b'D', include_value=True):
txid, vout = decode_key(k)
decrypt(v, secret)
height, coinbase, amount, sz = decode_val(v)
writer.writerow([txid, vout, height, coinbase, amount, sz])
def summarize(conn: leveldb.LevelDB):
counts = defaultdict(int)
for k, v in conn.RangeIter():
assert isinstance(k, bytearray)
kind = chr(k[0])
counts[kind] += 1
code_to_name = {t.value: t.name for t in RowType}
for k, v in sorted(
counts.items(), key=operator.itemgetter(1), reverse=True):
print('{:15s} {}'.format(code_to_name[k], v))
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
'-b',
'--blocks',
action='store_true',
help='Scan the block index (rather than chainstate)')
parser.add_argument(
'-t',
'--testnet',
action='store_true',
help='Testnet mode (ignored if --datadir is used)')
parser.add_argument(
'-s',
'--summarize',
action='store_true',
help='Summarize information about key types')
parser.add_argument('-d', '--database', help='Path to database directory')
args = parser.parse_args()
if args.database:
is_blocks = 'blocks/index' in args.dadatabase
conn = leveldb.LevelDB(args.database)
else:
is_blocks = args.blocks
db = locate_db(args.testnet, 'blocks/index'
if args.blocks else 'chainstate')
conn = leveldb.LevelDB(db)
try:
if is_blocks or args.summarize:
summarize(conn)
else:
dump_chainstate_csv(conn)
except (IOError, KeyboardInterrupt):
pass
if __name__ == '__main__':
main()