This repository has been archived by the owner on May 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 146
/
block.py
225 lines (181 loc) · 7.02 KB
/
block.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#
# Code for dumping a single block, given its ID (hash)
#
from bsddb.db import *
import logging
import os.path
import re
import sys
import time
from BCDataStream import *
from base58 import public_key_to_bc_address
from util import short_hex, long_hex
from deserialize import *
def _open_blkindex(db_env):
db = DB(db_env)
try:
r = db.open("blkindex.dat", "main", DB_BTREE, DB_THREAD|DB_RDONLY)
except DBError:
r = True
if r is not None:
logging.error("Couldn't open blkindex.dat/main. Try quitting any running Bitcoin apps.")
sys.exit(1)
return db
def _read_CDiskTxPos(stream):
n_file = stream.read_uint32()
n_block_pos = stream.read_uint32()
n_tx_pos = stream.read_uint32()
return (n_file, n_block_pos, n_tx_pos)
def _dump_block(datadir, nFile, nBlockPos, hash256, hashNext, do_print=True):
blockfile = open(os.path.join(datadir, "blk%04d.dat"%(nFile,)), "rb")
ds = BCDataStream()
ds.map_file(blockfile, nBlockPos)
d = parse_Block(ds)
block_string = deserialize_Block(d)
ds.close_file()
blockfile.close()
if do_print:
print "BLOCK "+long_hex(hash256[::-1])
print "Next block: "+long_hex(hashNext[::-1])
print block_string
return block_string
def _parse_block_index(vds):
d = {}
d['version'] = vds.read_int32()
d['hashNext'] = vds.read_bytes(32)
d['nFile'] = vds.read_uint32()
d['nBlockPos'] = vds.read_uint32()
d['nHeight'] = vds.read_int32()
d['b_version'] = vds.read_int32()
d['hashPrev'] = vds.read_bytes(32)
d['hashMerkle'] = vds.read_bytes(32)
d['nTime'] = vds.read_int32()
d['nBits'] = vds.read_int32()
d['nNonce'] = vds.read_int32()
return d
def dump_block(datadir, db_env, block_hash):
""" Dump a block, given hexadecimal hash-- either the full hash
OR a short_hex version of the it.
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
n_blockindex = 0
key_prefix = "\x0ablockindex"
cursor = db.cursor()
(key, value) = cursor.set_range(key_prefix)
while key.startswith(key_prefix):
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
hash256 = kds.read_bytes(32)
hash_hex = long_hex(hash256[::-1])
block_data = _parse_block_index(vds)
if (hash_hex.startswith(block_hash) or short_hex(hash256[::-1]).startswith(block_hash)):
print "Block height: "+str(block_data['nHeight'])
_dump_block(datadir, block_data['nFile'], block_data['nBlockPos'], hash256, block_data['hashNext'])
(key, value) = cursor.next()
db.close()
def read_block(db_cursor, hash):
(key,value) = db_cursor.set_range("\x0ablockindex"+hash)
vds = BCDataStream()
vds.clear(); vds.write(value)
block_data = _parse_block_index(vds)
block_data['hash256'] = hash
return block_data
def dump_block_n(datadir, db_env, block_number):
""" Dump a block given block number (== height, genesis block is 0)
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
block_data = read_block(cursor, hashBestChain)
while block_data['nHeight'] > block_number:
block_data = read_block(cursor, block_data['hashPrev'])
print "Block height: "+str(block_data['nHeight'])
_dump_block(datadir, block_data['nFile'], block_data['nBlockPos'], block_data['hash256'], block_data['hashNext'])
def search_blocks(datadir, db_env, pattern):
""" Dump a block given block number (== height, genesis block is 0)
"""
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
block_data = read_block(cursor, hashBestChain)
if pattern == "NONSTANDARD_CSCRIPTS": # Hack to look for non-standard transactions
search_odd_scripts(datadir, cursor, block_data)
return
while True:
block_string = _dump_block(datadir, block_data['nFile'], block_data['nBlockPos'],
block_data['hash256'], block_data['hashNext'], False)
if re.search(pattern, block_string) is not None:
print "MATCH: Block height: "+str(block_data['nHeight'])
print block_string
if block_data['nHeight'] == 0:
break
block_data = read_block(cursor, block_data['hashPrev'])
def search_odd_scripts(datadir, cursor, block_data):
""" Look for non-standard transactions """
while True:
block_string = _dump_block(datadir, block_data['nFile'], block_data['nBlockPos'],
block_data['hash256'], block_data['hashNext'], False)
import pdb
if block_data['nHeight'] == 71036:
pdb.set_trace()
found_nonstandard = False
for m in re.finditer(r'TxIn:(.*?)$', block_string, re.MULTILINE):
s = m.group(1)
if re.match(r'\s*COIN GENERATED coinbase:\w+$', s): continue
if re.match(r'.*sig: \d+:\w+...\w+ \d+:\w+...\w+$', s): continue
if re.match(r'.*sig: \d+:\w+...\w+$', s): continue
print "Nonstandard TxIn: "+s
found_nonstandard = True
break
for m in re.finditer(r'TxOut:(.*?)$', block_string, re.MULTILINE):
s = m.group(1)
if re.match(r'.*Script: DUP HASH160 \d+:\w+...\w+ EQUALVERIFY CHECKSIG$', s): continue
if re.match(r'.*Script: \d+:\w+...\w+ CHECKSIG$', s): continue
print "Nonstandard TxOut: "+s
found_nonstandard = True
break
if found_nonstandard:
print "NONSTANDARD TXN: Block height: "+str(block_data['nHeight'])
print block_string
if block_data['nHeight'] == 0:
break
block_data = read_block(cursor, block_data['hashPrev'])
def check_block_chain(db_env):
""" Make sure hashPrev/hashNext pointers are consistent through block chain """
db = _open_blkindex(db_env)
kds = BCDataStream()
vds = BCDataStream()
# Read the hashBestChain record:
cursor = db.cursor()
(key, value) = cursor.set_range("\x0dhashBestChain")
vds.write(value)
hashBestChain = vds.read_bytes(32)
back_blocks = []
block_data = read_block(cursor, hashBestChain)
while block_data['nHeight'] > 0:
back_blocks.append( (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext']) )
block_data = read_block(cursor, block_data['hashPrev'])
back_blocks.append( (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext']) )
genesis_block = block_data
print("check block chain: genesis block merkle hash is: %s"%(block_data['hashMerkle'][::-1].encode('hex_codec')))
while block_data['hashNext'] != ('\0'*32):
forward = (block_data['nHeight'], block_data['hashMerkle'], block_data['hashPrev'], block_data['hashNext'])
back = back_blocks.pop()
if forward != back:
print("Forward/back block mismatch at height %d!"%(block_data['nHeight'],))
print(" Forward: "+str(forward))
print(" Back: "+str(back))
block_data = read_block(cursor, block_data['hashNext'])