2013-09-01 09:16:15 -07:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Electrum - lightweight Bitcoin client
|
|
|
|
# Copyright (C) 2012 thomasv@ecdsa.org
|
|
|
|
#
|
2016-02-23 02:36:42 -08:00
|
|
|
# Permission is hereby granted, free of charge, to any person
|
|
|
|
# obtaining a copy of this software and associated documentation files
|
|
|
|
# (the "Software"), to deal in the Software without restriction,
|
|
|
|
# including without limitation the rights to use, copy, modify, merge,
|
|
|
|
# publish, distribute, sublicense, and/or sell copies of the Software,
|
|
|
|
# and to permit persons to whom the Software is furnished to do so,
|
|
|
|
# subject to the following conditions:
|
2013-09-01 09:16:15 -07:00
|
|
|
#
|
2016-02-23 02:36:42 -08:00
|
|
|
# The above copyright notice and this permission notice shall be
|
|
|
|
# included in all copies or substantial portions of the Software.
|
2013-09-01 09:16:15 -07:00
|
|
|
#
|
2016-02-23 02:36:42 -08:00
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
|
|
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
|
|
|
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
|
|
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
|
|
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
|
2015-05-17 06:54:20 -07:00
|
|
|
import os
|
2015-03-13 15:04:29 -07:00
|
|
|
import util
|
2017-01-07 07:58:23 -08:00
|
|
|
import bitcoin
|
2013-09-01 09:16:15 -07:00
|
|
|
from bitcoin import *
|
|
|
|
|
2015-12-11 03:37:40 -08:00
|
|
|
MAX_TARGET = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2017-05-29 00:03:39 -07:00
|
|
|
def serialize_header(res):
|
|
|
|
s = int_to_hex(res.get('version'), 4) \
|
|
|
|
+ rev_hex(res.get('prev_block_hash')) \
|
|
|
|
+ rev_hex(res.get('merkle_root')) \
|
|
|
|
+ int_to_hex(int(res.get('timestamp')), 4) \
|
|
|
|
+ int_to_hex(int(res.get('bits')), 4) \
|
|
|
|
+ int_to_hex(int(res.get('nonce')), 4)
|
|
|
|
return s
|
|
|
|
|
|
|
|
def deserialize_header(s, height):
|
|
|
|
hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16)
|
|
|
|
h = {}
|
|
|
|
h['version'] = hex_to_int(s[0:4])
|
|
|
|
h['prev_block_hash'] = hash_encode(s[4:36])
|
|
|
|
h['merkle_root'] = hash_encode(s[36:68])
|
|
|
|
h['timestamp'] = hex_to_int(s[68:72])
|
|
|
|
h['bits'] = hex_to_int(s[72:76])
|
|
|
|
h['nonce'] = hex_to_int(s[76:80])
|
|
|
|
h['block_height'] = height
|
|
|
|
return h
|
|
|
|
|
|
|
|
def hash_header(header):
|
|
|
|
if header is None:
|
|
|
|
return '0' * 64
|
|
|
|
if header.get('prev_block_hash') is None:
|
|
|
|
header['prev_block_hash'] = '00'*32
|
|
|
|
return hash_encode(Hash(serialize_header(header).decode('hex')))
|
|
|
|
|
|
|
|
|
2017-07-15 08:20:06 -07:00
|
|
|
blockchains = {}
|
|
|
|
|
|
|
|
def read_blockchains(config):
|
|
|
|
blockchains[0] = Blockchain(config, 'blockchain_headers')
|
2017-07-18 09:10:22 -07:00
|
|
|
l = filter(lambda x: x.startswith('fork_'), os.listdir(config.path))
|
|
|
|
l = sorted(l, key = lambda x: int(x.split('_')[1]))
|
2017-07-16 23:44:09 -07:00
|
|
|
for x in l:
|
|
|
|
b = Blockchain(config, x)
|
|
|
|
blockchains[b.checkpoint] = b
|
2017-07-15 08:20:06 -07:00
|
|
|
return blockchains
|
|
|
|
|
2017-07-17 10:32:10 -07:00
|
|
|
def check_header(header):
|
2017-07-15 08:20:06 -07:00
|
|
|
if type(header) is not dict:
|
|
|
|
return False
|
|
|
|
for b in blockchains.values():
|
2017-07-16 23:44:09 -07:00
|
|
|
if b.check_header(header):
|
2017-07-15 08:20:06 -07:00
|
|
|
return b
|
|
|
|
return False
|
|
|
|
|
2017-07-17 10:32:10 -07:00
|
|
|
def can_connect(header):
|
|
|
|
for b in blockchains.values():
|
|
|
|
if b.can_connect(header):
|
|
|
|
return b
|
|
|
|
return False
|
2017-07-15 08:20:06 -07:00
|
|
|
|
|
|
|
|
2015-09-06 05:40:00 -07:00
|
|
|
class Blockchain(util.PrintError):
|
2017-07-13 07:23:41 -07:00
|
|
|
|
2015-05-17 06:54:20 -07:00
|
|
|
'''Manages blockchain headers and their verification'''
|
2017-07-13 07:23:41 -07:00
|
|
|
|
2017-07-15 04:51:40 -07:00
|
|
|
def __init__(self, config, filename):
|
2013-09-01 09:16:15 -07:00
|
|
|
self.config = config
|
2017-07-13 07:23:41 -07:00
|
|
|
self.filename = filename
|
2017-05-29 00:03:39 -07:00
|
|
|
self.catch_up = None # interface catching up
|
2017-07-15 04:51:40 -07:00
|
|
|
self.is_saved = True
|
2017-07-13 07:23:41 -07:00
|
|
|
self.headers = []
|
2017-07-15 08:20:06 -07:00
|
|
|
if filename == 'blockchain_headers':
|
|
|
|
self.parent = None
|
|
|
|
self.checkpoint = 0
|
|
|
|
elif filename.startswith('fork_'):
|
|
|
|
self.parent = blockchains[int(filename.split('_')[1])]
|
|
|
|
self.checkpoint = int(filename.split('_')[2])
|
|
|
|
else:
|
|
|
|
raise BaseException('')
|
2017-07-16 23:44:09 -07:00
|
|
|
|
2017-07-18 09:10:22 -07:00
|
|
|
def get_max_child(self):
|
|
|
|
children = filter(lambda y: y.parent==self, blockchains.values())
|
|
|
|
return max([x.checkpoint for x in children]) if children else None
|
|
|
|
|
|
|
|
def get_branch_size(self):
|
|
|
|
mc = self.get_max_child()
|
|
|
|
checkpoint = mc if mc is not None else self.checkpoint
|
|
|
|
return self.height() - checkpoint
|
|
|
|
|
2017-07-16 23:44:09 -07:00
|
|
|
def check_header(self, header):
|
|
|
|
header_hash = hash_header(header)
|
|
|
|
height = header.get('block_height')
|
|
|
|
return header_hash == self.get_hash(height)
|
2015-05-08 04:43:42 -07:00
|
|
|
|
2017-07-15 08:20:06 -07:00
|
|
|
def fork(parent, checkpoint):
|
|
|
|
filename = 'fork_%d_%d'%(parent.checkpoint, checkpoint)
|
|
|
|
self = Blockchain(parent.config, filename)
|
2017-07-15 04:51:40 -07:00
|
|
|
self.is_saved = False
|
|
|
|
return self
|
|
|
|
|
2015-05-08 04:43:42 -07:00
|
|
|
def height(self):
|
2017-07-16 23:44:09 -07:00
|
|
|
return self.checkpoint + self.size() - 1
|
|
|
|
|
|
|
|
def size(self):
|
|
|
|
if self.is_saved:
|
|
|
|
p = self.path()
|
|
|
|
return os.path.getsize(p)/80 if os.path.exists(p) else 0
|
|
|
|
else:
|
|
|
|
return len(self.headers)
|
2013-09-02 08:49:12 -07:00
|
|
|
|
2015-12-12 04:43:07 -08:00
|
|
|
def verify_header(self, header, prev_header, bits, target):
|
2017-05-29 00:03:39 -07:00
|
|
|
prev_hash = hash_header(prev_header)
|
|
|
|
_hash = hash_header(header)
|
2017-03-23 03:58:56 -07:00
|
|
|
if prev_hash != header.get('prev_block_hash'):
|
|
|
|
raise BaseException("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')))
|
|
|
|
if bitcoin.TESTNET:
|
|
|
|
return
|
|
|
|
if bits != header.get('bits'):
|
|
|
|
raise BaseException("bits mismatch: %s vs %s" % (bits, header.get('bits')))
|
|
|
|
if int('0x' + _hash, 16) > target:
|
|
|
|
raise BaseException("insufficient proof of work: %s vs target %s" % (int('0x' + _hash, 16), target))
|
2015-12-11 03:37:40 -08:00
|
|
|
|
2013-09-02 08:49:12 -07:00
|
|
|
def verify_chain(self, chain):
|
|
|
|
first_header = chain[0]
|
2015-12-12 04:43:07 -08:00
|
|
|
prev_header = self.read_header(first_header.get('block_height') - 1)
|
2013-09-02 08:49:12 -07:00
|
|
|
for header in chain:
|
|
|
|
height = header.get('block_height')
|
2015-12-12 04:43:07 -08:00
|
|
|
bits, target = self.get_target(height / 2016, chain)
|
|
|
|
self.verify_header(header, prev_header, bits, target)
|
2013-09-02 08:49:12 -07:00
|
|
|
prev_header = header
|
|
|
|
|
2015-12-12 21:33:06 -08:00
|
|
|
def verify_chunk(self, index, data):
|
2015-12-12 04:43:07 -08:00
|
|
|
num = len(data) / 80
|
|
|
|
prev_header = None
|
|
|
|
if index != 0:
|
|
|
|
prev_header = self.read_header(index*2016 - 1)
|
2013-09-01 09:16:15 -07:00
|
|
|
bits, target = self.get_target(index)
|
|
|
|
for i in range(num):
|
2015-12-12 04:43:07 -08:00
|
|
|
raw_header = data[i*80:(i+1) * 80]
|
2017-05-29 00:03:39 -07:00
|
|
|
header = deserialize_header(raw_header, index*2016 + i)
|
2015-12-12 04:43:07 -08:00
|
|
|
self.verify_header(header, prev_header, bits, target)
|
2015-12-11 03:37:40 -08:00
|
|
|
prev_header = header
|
2014-10-21 10:05:51 -07:00
|
|
|
|
2013-09-01 09:16:15 -07:00
|
|
|
def path(self):
|
2017-05-29 00:03:39 -07:00
|
|
|
d = util.get_headers_dir(self.config)
|
|
|
|
return os.path.join(d, self.filename)
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
def save_chunk(self, index, chunk):
|
2017-07-13 07:23:41 -07:00
|
|
|
if not self.is_saved:
|
2017-07-15 04:51:40 -07:00
|
|
|
self.save()
|
2013-09-01 09:16:15 -07:00
|
|
|
filename = self.path()
|
2017-07-16 23:44:09 -07:00
|
|
|
d = (index * 2016 - self.checkpoint) * 80
|
|
|
|
if d < 0:
|
|
|
|
chunk = chunk[-d:]
|
|
|
|
d = 0
|
2017-07-13 07:23:41 -07:00
|
|
|
with open(filename, 'rb+') as f:
|
2017-07-16 23:44:09 -07:00
|
|
|
f.seek(d)
|
|
|
|
f.write(chunk)
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2017-07-15 04:51:40 -07:00
|
|
|
def save(self):
|
2017-07-15 08:20:06 -07:00
|
|
|
# recursively save parents if they have not been saved
|
2017-07-15 23:07:47 -07:00
|
|
|
if self.parent and not self.parent.is_saved:
|
2017-07-15 08:20:06 -07:00
|
|
|
self.parent.save()
|
|
|
|
open(self.path(), 'w+').close()
|
2017-07-13 07:23:41 -07:00
|
|
|
for h in self.headers:
|
|
|
|
self.write_header(h)
|
|
|
|
self.headers = []
|
2017-07-15 08:20:06 -07:00
|
|
|
self.is_saved = True
|
|
|
|
self.print_error("saved", self.filename)
|
2017-07-13 07:23:41 -07:00
|
|
|
|
2017-07-18 09:10:22 -07:00
|
|
|
def swap_with_parent(self):
|
|
|
|
self.print_error("swap")
|
|
|
|
parent = self.parent
|
|
|
|
checkpoint = self.checkpoint
|
|
|
|
# copy headers
|
|
|
|
parent.headers = [parent.read_header(h) for h in range(checkpoint, checkpoint + parent.get_branch_size())]
|
|
|
|
# truncate parent file
|
|
|
|
with open(parent.path(), 'rb+') as f:
|
|
|
|
f.seek(checkpoint*80)
|
|
|
|
f.truncate()
|
|
|
|
parent.is_saved = False
|
|
|
|
# swap chains
|
|
|
|
fn = self.filename; self.filename = parent.filename; parent.filename = fn
|
|
|
|
self.parent = parent.parent; parent.parent = parent
|
|
|
|
self.checkpoint = parent.checkpoint; parent.checkpoint = checkpoint
|
|
|
|
# write my headers
|
|
|
|
for h in self.headers:
|
|
|
|
self.write_header(h)
|
|
|
|
self.headers = []
|
|
|
|
self.is_saved = True
|
|
|
|
|
2013-09-01 09:16:15 -07:00
|
|
|
def save_header(self, header):
|
2017-07-18 09:10:22 -07:00
|
|
|
N = 10
|
2017-07-13 07:23:41 -07:00
|
|
|
height = header.get('block_height')
|
|
|
|
if not self.is_saved:
|
2017-07-13 21:20:05 -07:00
|
|
|
assert height == self.checkpoint + len(self.headers)
|
2017-07-13 07:23:41 -07:00
|
|
|
self.headers.append(header)
|
2017-07-18 09:10:22 -07:00
|
|
|
if len(self.headers) > N:
|
|
|
|
if self.parent.get_branch_size() <= N:
|
|
|
|
self.swap_with_parent()
|
|
|
|
else:
|
|
|
|
self.save()
|
2017-07-13 07:23:41 -07:00
|
|
|
return
|
|
|
|
self.write_header(header)
|
|
|
|
|
|
|
|
def write_header(self, header):
|
2017-07-16 23:44:09 -07:00
|
|
|
filename = self.path()
|
2017-07-15 08:20:06 -07:00
|
|
|
delta = header.get('block_height') - self.checkpoint
|
2017-05-29 00:03:39 -07:00
|
|
|
data = serialize_header(header).decode('hex')
|
2017-07-16 23:44:09 -07:00
|
|
|
assert delta * 80 == os.path.getsize(filename)
|
2013-09-01 09:16:15 -07:00
|
|
|
assert len(data) == 80
|
2017-07-13 07:23:41 -07:00
|
|
|
with open(filename, 'rb+') as f:
|
2017-07-15 08:20:06 -07:00
|
|
|
f.seek(delta * 80)
|
2017-07-16 23:44:09 -07:00
|
|
|
f.write(data)
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2017-07-13 07:23:41 -07:00
|
|
|
def read_header(self, height):
|
2017-07-15 08:20:06 -07:00
|
|
|
if height < self.checkpoint:
|
|
|
|
return self.parent.read_header(height)
|
|
|
|
delta = height - self.checkpoint
|
|
|
|
if not self.is_saved:
|
|
|
|
if delta >= len(self.headers):
|
2017-07-13 07:23:41 -07:00
|
|
|
return None
|
2017-07-15 08:20:06 -07:00
|
|
|
header = self.headers[delta]
|
2017-07-13 07:23:41 -07:00
|
|
|
assert header.get('block_height') == height
|
|
|
|
return header
|
2013-09-01 09:16:15 -07:00
|
|
|
name = self.path()
|
|
|
|
if os.path.exists(name):
|
2015-12-12 04:43:07 -08:00
|
|
|
f = open(name, 'rb')
|
2017-07-15 08:20:06 -07:00
|
|
|
f.seek(delta * 80)
|
2013-09-01 09:16:15 -07:00
|
|
|
h = f.read(80)
|
|
|
|
f.close()
|
|
|
|
if len(h) == 80:
|
2017-07-16 23:44:09 -07:00
|
|
|
h = deserialize_header(h, height)
|
2014-10-21 10:05:51 -07:00
|
|
|
return h
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2017-05-29 00:03:39 -07:00
|
|
|
def get_hash(self, height):
|
|
|
|
return bitcoin.GENESIS if height == 0 else hash_header(self.read_header(height))
|
|
|
|
|
2017-03-25 03:09:24 -07:00
|
|
|
def BIP9(self, height, flag):
|
|
|
|
v = self.read_header(height)['version']
|
|
|
|
return ((v & 0xE0000000) == 0x20000000) and ((v & flag) == flag)
|
|
|
|
|
|
|
|
def segwit_support(self, N=144):
|
|
|
|
h = self.local_height
|
|
|
|
return sum([self.BIP9(h-i, 2) for i in range(N)])*10000/N/100.
|
|
|
|
|
2017-05-18 23:55:40 -07:00
|
|
|
def truncate_headers(self, height):
|
|
|
|
self.print_error('Truncating headers file at height %d'%height)
|
2017-03-23 03:58:56 -07:00
|
|
|
name = self.path()
|
2017-03-26 15:46:44 -07:00
|
|
|
f = open(name, 'rb+')
|
2017-05-18 23:55:40 -07:00
|
|
|
f.seek(height * 80)
|
2017-03-23 03:58:56 -07:00
|
|
|
f.truncate()
|
|
|
|
f.close()
|
|
|
|
|
2014-06-25 08:43:45 -07:00
|
|
|
def get_target(self, index, chain=None):
|
2017-03-23 03:58:56 -07:00
|
|
|
if bitcoin.TESTNET:
|
|
|
|
return 0, 0
|
2015-12-11 03:37:40 -08:00
|
|
|
if index == 0:
|
|
|
|
return 0x1d00ffff, MAX_TARGET
|
2015-12-12 04:43:07 -08:00
|
|
|
first = self.read_header((index-1) * 2016)
|
|
|
|
last = self.read_header(index*2016 - 1)
|
2013-10-16 05:42:52 -07:00
|
|
|
if last is None:
|
|
|
|
for h in chain:
|
2015-12-12 04:43:07 -08:00
|
|
|
if h.get('block_height') == index*2016 - 1:
|
2013-10-16 05:42:52 -07:00
|
|
|
last = h
|
2015-12-11 03:37:40 -08:00
|
|
|
assert last is not None
|
2015-11-19 09:43:57 -08:00
|
|
|
# bits to target
|
|
|
|
bits = last.get('bits')
|
|
|
|
bitsN = (bits >> 24) & 0xff
|
2017-03-23 03:58:56 -07:00
|
|
|
if not (bitsN >= 0x03 and bitsN <= 0x1d):
|
|
|
|
raise BaseException("First part of bits should be in [0x03, 0x1d]")
|
2015-11-19 09:43:57 -08:00
|
|
|
bitsBase = bits & 0xffffff
|
2017-03-23 03:58:56 -07:00
|
|
|
if not (bitsBase >= 0x8000 and bitsBase <= 0x7fffff):
|
|
|
|
raise BaseException("Second part of bits should be in [0x8000, 0x7fffff]")
|
2015-12-12 04:43:07 -08:00
|
|
|
target = bitsBase << (8 * (bitsN-3))
|
2015-11-19 09:43:57 -08:00
|
|
|
# new target
|
2013-09-01 09:16:15 -07:00
|
|
|
nActualTimespan = last.get('timestamp') - first.get('timestamp')
|
2015-12-12 04:43:07 -08:00
|
|
|
nTargetTimespan = 14 * 24 * 60 * 60
|
|
|
|
nActualTimespan = max(nActualTimespan, nTargetTimespan / 4)
|
|
|
|
nActualTimespan = min(nActualTimespan, nTargetTimespan * 4)
|
|
|
|
new_target = min(MAX_TARGET, (target*nActualTimespan) / nTargetTimespan)
|
2015-11-19 09:43:57 -08:00
|
|
|
# convert new target to bits
|
|
|
|
c = ("%064x" % new_target)[2:]
|
|
|
|
while c[:2] == '00' and len(c) > 6:
|
2013-09-01 09:16:15 -07:00
|
|
|
c = c[2:]
|
2015-12-12 04:43:07 -08:00
|
|
|
bitsN, bitsBase = len(c) / 2, int('0x' + c[:6], 16)
|
2015-11-19 09:43:57 -08:00
|
|
|
if bitsBase >= 0x800000:
|
|
|
|
bitsN += 1
|
|
|
|
bitsBase >>= 8
|
|
|
|
new_bits = bitsN << 24 | bitsBase
|
2015-12-12 04:43:07 -08:00
|
|
|
return new_bits, bitsBase << (8 * (bitsN-3))
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2017-03-31 03:45:09 -07:00
|
|
|
def can_connect(self, header):
|
2017-07-18 12:32:34 -07:00
|
|
|
height = header['block_height']
|
|
|
|
if self.height() != height - 1:
|
|
|
|
return False
|
|
|
|
previous_header = self.read_header(height -1)
|
2015-05-17 06:54:20 -07:00
|
|
|
if not previous_header:
|
2017-03-31 03:45:09 -07:00
|
|
|
return False
|
2017-05-29 00:03:39 -07:00
|
|
|
prev_hash = hash_header(previous_header)
|
2015-05-17 06:54:20 -07:00
|
|
|
if prev_hash != header.get('prev_block_hash'):
|
2017-03-31 03:45:09 -07:00
|
|
|
return False
|
|
|
|
bits, target = self.get_target(height / 2016)
|
2015-12-11 03:37:40 -08:00
|
|
|
try:
|
2017-03-31 03:45:09 -07:00
|
|
|
self.verify_header(header, previous_header, bits, target)
|
|
|
|
except:
|
2015-12-11 03:37:40 -08:00
|
|
|
return False
|
2017-03-31 03:45:09 -07:00
|
|
|
return True
|
2015-05-17 06:54:20 -07:00
|
|
|
|
2015-12-12 21:33:06 -08:00
|
|
|
def connect_chunk(self, idx, hexdata):
|
2015-05-17 06:54:20 -07:00
|
|
|
try:
|
2015-12-12 21:33:06 -08:00
|
|
|
data = hexdata.decode('hex')
|
|
|
|
self.verify_chunk(idx, data)
|
2017-05-29 00:03:39 -07:00
|
|
|
#self.print_error("validated chunk %d" % idx)
|
2015-12-12 21:33:06 -08:00
|
|
|
self.save_chunk(idx, data)
|
2017-03-31 03:45:09 -07:00
|
|
|
return True
|
2015-12-11 03:37:40 -08:00
|
|
|
except BaseException as e:
|
|
|
|
self.print_error('verify_chunk failed', str(e))
|
2017-03-31 03:45:09 -07:00
|
|
|
return False
|