electrum-bitcoinprivate/lib/blockchain.py

401 lines
14 KiB
Python
Raw Normal View History

# 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:
#
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.
#
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.
import os
2017-07-24 06:54:42 -07:00
import threading
2017-01-22 10:25:24 -08:00
from . import util
from . import bitcoin
from .bitcoin import *
2018-04-01 16:31:13 -07:00
HDR_LEN = 1487
CHUNK_LEN = 100
2018-04-01 16:31:13 -07:00
POW_LIMIT = 0x0007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
POW_AVERAGING_WINDOW = 17
POW_MEDIAN_BLOCK_SPAN = 11
POW_MAX_ADJUST_DOWN = 32
POW_MAX_ADJUST_UP = 16
POW_DAMPING_FACTOR = 4
POW_TARGET_SPACING = 150
AVERAGING_WINDOW_TIMESPAN = POW_AVERAGING_WINDOW * POW_TARGET_SPACING
MIN_ACTUAL_TIMESPAN = AVERAGING_WINDOW_TIMESPAN * \
(100 - POW_MAX_ADJUST_UP) // 100
MAX_ACTUAL_TIMESPAN = AVERAGING_WINDOW_TIMESPAN * \
(100 + POW_MAX_ADJUST_DOWN) // 100
def bits_to_target(bits):
"""Convert a compact representation to a hex target."""
MM = 256 * 256 * 256
a = bits % MM
if a < 0x8000:
a *= 256
target = a * pow(2, 8 * (bits // MM - 3))
return target
def target_to_bits(target):
"""Convert a target to compact representation."""
MM = 256 * 256 * 256
c = ('%064X' % target)[2:]
i = 31
while c[0:2] == '00':
c = c[2:]
i -= 1
c = int('0x%s' % c[0:6], 16)
if c >= 0x800000:
c //= 256
i += 1
new_bits = c + MM * i
return new_bits
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')) \
+ rev_hex(res.get('reserved_hash')) \
+ int_to_hex(int(res.get('timestamp')), 4) \
+ int_to_hex(int(res.get('bits')), 4) \
+ rev_hex(res.get('nonce')) \
+ rev_hex(res.get('sol_size')) \
+ rev_hex(res.get('solution'))
return s
def deserialize_header(s, height):
2017-03-15 04:13:20 -07:00
hex_to_int = lambda s: int('0x' + bh2u(s[::-1]), 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['reserved_hash'] = hash_encode(s[68:100])
h['timestamp'] = hex_to_int(s[100:104])
h['bits'] = hex_to_int(s[104:108])
h['nonce'] = hash_encode(s[108:140])
h['sol_size'] = hash_encode(s[140:143])
h['solution'] = hash_encode(s[143:1487])
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
2017-03-15 04:13:20 -07:00
return hash_encode(Hash(bfh(serialize_header(header))))
blockchains = {}
def read_blockchains(config):
2017-07-19 02:26:13 -07:00
blockchains[0] = Blockchain(config, 0, None)
2017-07-20 12:28:27 -07:00
fdir = os.path.join(util.get_headers_dir(config), 'forks')
if not os.path.exists(fdir):
os.mkdir(fdir)
l = filter(lambda x: x.startswith('fork_'), os.listdir(fdir))
l = sorted(l, key = lambda x: int(x.split('_')[1]))
2017-07-19 02:26:13 -07:00
for filename in l:
checkpoint = int(filename.split('_')[2])
parent_id = int(filename.split('_')[1])
b = Blockchain(config, checkpoint, parent_id)
2017-07-16 23:44:09 -07:00
blockchains[b.checkpoint] = b
return blockchains
def check_header(header):
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):
return b
return False
def can_connect(header):
for b in blockchains.values():
if b.can_connect(header):
return b
return False
class Blockchain(util.PrintError):
2017-02-04 06:48:13 -08:00
"""
Manages blockchain headers and their verification
"""
def __init__(self, config, checkpoint, parent_id):
self.config = config
self.catch_up = None # interface catching up
2017-07-19 02:26:13 -07:00
self.checkpoint = checkpoint
self.parent_id = parent_id
2017-07-24 06:54:42 -07:00
self.lock = threading.Lock()
with self.lock:
self.update_size()
def parent(self):
return blockchains[self.parent_id]
2017-07-16 23:44:09 -07:00
def get_max_child(self):
2017-03-15 04:13:20 -07:00
children = list(filter(lambda y: y.parent_id==self.checkpoint, blockchains.values()))
return max([x.checkpoint for x in children]) if children else None
def get_checkpoint(self):
mc = self.get_max_child()
return mc if mc is not None else self.checkpoint
def get_branch_size(self):
return self.height() - self.get_checkpoint() + 1
def get_name(self):
return self.get_hash(self.get_checkpoint()).lstrip('00')[0:10]
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)
2017-07-24 06:54:42 -07:00
def fork(parent, header):
checkpoint = header.get('block_height')
self = Blockchain(parent.config, checkpoint, parent.checkpoint)
2017-07-19 02:14:11 -07:00
open(self.path(), 'w+').close()
2017-07-24 06:54:42 -07:00
self.save_header(header)
2017-07-15 04:51:40 -07:00
return self
def height(self):
2017-07-16 23:44:09 -07:00
return self.checkpoint + self.size() - 1
def size(self):
2017-07-24 06:54:42 -07:00
with self.lock:
return self._size
def update_size(self):
2017-07-19 02:14:11 -07:00
p = self.path()
self._size = os.path.getsize(p)//HDR_LEN if os.path.exists(p) else 0
2015-12-12 04:43:07 -08:00
def verify_header(self, header, prev_header, bits, target):
prev_hash = hash_header(prev_header)
_hash = hash_header(header)
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.NetworkConstants.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
2015-12-12 21:33:06 -08:00
def verify_chunk(self, index, data):
num = len(data) // HDR_LEN
2015-12-12 04:43:07 -08:00
prev_header = None
if index != 0:
prev_header = self.read_header(index * CHUNK_LEN - 1)
2018-04-01 16:31:13 -07:00
chain = []
for i in range(num):
raw_header = data[i*HDR_LEN:(i+1) * HDR_LEN]
header = deserialize_header(raw_header, index*CHUNK_LEN + i)
2018-04-01 16:31:13 -07:00
height = index * CHUNK_LEN + i
header['block_height'] = height
chain.append(header)
bits, target = self.get_target(height, chain)
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
def path(self):
d = util.get_headers_dir(self.config)
filename = 'blockchain_headers' if self.parent_id is None else os.path.join('forks', 'fork_%d_%d'%(self.parent_id, self.checkpoint))
2017-07-19 02:26:13 -07:00
return os.path.join(d, filename)
def save_chunk(self, index, chunk):
filename = self.path()
d = (index * CHUNK_LEN - self.checkpoint) * HDR_LEN
2017-07-16 23:44:09 -07:00
if d < 0:
chunk = chunk[-d:]
d = 0
self.write(chunk, d)
self.swap_with_parent()
def swap_with_parent(self):
if self.parent_id is None:
return
parent_branch_size = self.parent().height() - self.checkpoint + 1
if parent_branch_size >= self.size():
return
self.print_error("swap", self.checkpoint, self.parent_id)
parent_id = self.parent_id
checkpoint = self.checkpoint
parent = self.parent()
with open(self.path(), 'rb') as f:
my_data = f.read()
with open(parent.path(), 'rb') as f:
f.seek((checkpoint - parent.checkpoint)*HDR_LEN)
parent_data = f.read(parent_branch_size*HDR_LEN)
self.write(parent_data, 0)
parent.write(my_data, (checkpoint - parent.checkpoint)*HDR_LEN)
# store file path
for b in blockchains.values():
b.old_path = b.path()
2017-07-19 02:14:11 -07:00
# swap parameters
self.parent_id = parent.parent_id; parent.parent_id = parent_id
self.checkpoint = parent.checkpoint; parent.checkpoint = checkpoint
self._size = parent._size; parent._size = parent_branch_size
# move files
for b in blockchains.values():
if b in [self, parent]: continue
if b.old_path != b.path():
self.print_error("renaming", b.old_path, b.path())
os.rename(b.old_path, b.path())
2017-07-18 21:46:37 -07:00
# update pointers
blockchains[self.checkpoint] = self
blockchains[parent.checkpoint] = parent
def write(self, data, offset):
2017-07-16 23:44:09 -07:00
filename = self.path()
2017-07-24 06:54:42 -07:00
with self.lock:
with open(filename, 'rb+') as f:
if offset != self._size*HDR_LEN:
f.seek(offset)
f.truncate()
f.seek(offset)
2017-07-24 06:54:42 -07:00
f.write(data)
f.flush()
os.fsync(f.fileno())
2017-07-24 06:54:42 -07:00
self.update_size()
def save_header(self, header):
delta = header.get('block_height') - self.checkpoint
2017-03-15 04:13:20 -07:00
data = bfh(serialize_header(header))
assert delta == self.size()
assert len(data) == HDR_LEN
self.write(data, delta*HDR_LEN)
self.swap_with_parent()
def read_header(self, height):
assert self.parent_id != self.checkpoint
2017-08-01 02:00:12 -07:00
if height < 0:
return
if height < self.checkpoint:
return self.parent().read_header(height)
2017-07-19 05:26:44 -07:00
if height > self.height():
return
delta = height - self.checkpoint
name = self.path()
if os.path.exists(name):
2017-11-12 05:33:46 -08:00
with open(name, 'rb') as f:
f.seek(delta * HDR_LEN)
h = f.read(HDR_LEN)
2017-07-19 05:26:44 -07:00
return deserialize_header(h, height)
def get_hash(self, height):
return hash_header(self.read_header(height))
2018-06-06 09:58:37 -07:00
def get_median_time(self, height, chain=None):
if chain is None:
chain = []
2018-04-01 16:31:13 -07:00
height_range = range(max(0, height - POW_MEDIAN_BLOCK_SPAN),
max(1, height))
median = []
for h in height_range:
header = self.read_header(h)
if not header:
for header in chain:
if header.get('block_height') == h:
break
assert header and header.get('block_height') == h
median.append(header.get('timestamp'))
median.sort()
return median[len(median)//2];
2018-06-06 09:58:37 -07:00
def get_target(self, height, chain=None):
if chain is None:
chain = []
if bitcoin.NetworkConstants.TESTNET:
return 0, 0
2018-04-01 16:31:13 -07:00
if height <= POW_AVERAGING_WINDOW:
return target_to_bits(POW_LIMIT), POW_LIMIT
height_range = range(max(0, height - POW_AVERAGING_WINDOW),
max(1, height))
mean_target = 0
for h in height_range:
header = self.read_header(h)
if not header:
for header in chain:
if header.get('block_height') == h:
break
assert header and header.get('block_height') == h
mean_target += bits_to_target(header.get('bits'))
mean_target //= POW_AVERAGING_WINDOW
actual_timespan = self.get_median_time(height, chain) - \
self.get_median_time(height - POW_AVERAGING_WINDOW, chain)
actual_timespan = AVERAGING_WINDOW_TIMESPAN + \
int((actual_timespan - AVERAGING_WINDOW_TIMESPAN) / \
POW_DAMPING_FACTOR)
if actual_timespan < MIN_ACTUAL_TIMESPAN:
actual_timespan = MIN_ACTUAL_TIMESPAN
elif actual_timespan > MAX_ACTUAL_TIMESPAN:
actual_timespan = MAX_ACTUAL_TIMESPAN
next_target = mean_target // AVERAGING_WINDOW_TIMESPAN * actual_timespan
if next_target > POW_LIMIT:
next_target = POW_LIMIT
return target_to_bits(next_target), next_target
def can_connect(self, header, check_height=True):
2017-07-18 12:32:34 -07:00
height = header['block_height']
if check_height and self.height() != height - 1:
2017-07-18 12:32:34 -07:00
return False
2017-07-19 08:23:46 -07:00
if height == 0:
return hash_header(header) == bitcoin.NetworkConstants.GENESIS
2017-07-18 12:32:34 -07:00
previous_header = self.read_header(height -1)
if not previous_header:
return False
prev_hash = hash_header(previous_header)
if prev_hash != header.get('prev_block_hash'):
return False
2018-04-01 16:31:13 -07:00
bits, target = self.get_target(height)
2015-12-11 03:37:40 -08:00
try:
self.verify_header(header, previous_header, bits, target)
except:
2015-12-11 03:37:40 -08:00
return False
return True
2015-12-12 21:33:06 -08:00
def connect_chunk(self, idx, hexdata):
try:
2017-02-04 06:48:13 -08:00
data = bfh(hexdata)
2015-12-12 21:33:06 -08:00
self.verify_chunk(idx, data)
#self.print_error("validated chunk %d" % idx)
2015-12-12 21:33:06 -08:00
self.save_chunk(idx, data)
return True
2015-12-11 03:37:40 -08:00
except BaseException as e:
self.print_error('verify_chunk failed', str(e))
return False