2013-09-01 09:16:15 -07:00
|
|
|
#!/usr/bin/env python
|
|
|
|
#
|
|
|
|
# Electrum - lightweight Bitcoin client
|
|
|
|
# Copyright (C) 2012 thomasv@ecdsa.org
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
|
2015-05-17 06:54:20 -07:00
|
|
|
import os
|
2015-03-13 15:04:29 -07:00
|
|
|
import util
|
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
|
|
|
|
2015-09-06 05:40:00 -07:00
|
|
|
class Blockchain(util.PrintError):
|
2015-05-17 06:54:20 -07:00
|
|
|
'''Manages blockchain headers and their verification'''
|
2013-09-10 09:27:32 -07:00
|
|
|
def __init__(self, config, network):
|
2013-09-01 09:16:15 -07:00
|
|
|
self.config = config
|
2013-09-10 09:27:32 -07:00
|
|
|
self.network = network
|
2015-07-18 02:17:19 -07:00
|
|
|
self.headers_url = 'https://headers.electrum.org/blockchain_headers'
|
2015-05-08 04:43:42 -07:00
|
|
|
self.local_height = 0
|
|
|
|
self.set_local_height()
|
|
|
|
|
|
|
|
def height(self):
|
|
|
|
return self.local_height
|
2013-09-02 08:49:12 -07:00
|
|
|
|
2015-05-17 06:54:20 -07:00
|
|
|
def init(self):
|
2013-09-08 08:23:01 -07:00
|
|
|
self.init_headers_file()
|
2015-06-13 07:45:42 -07:00
|
|
|
self.set_local_height()
|
2015-05-08 04:43:42 -07:00
|
|
|
self.print_error("%d blocks" % self.local_height)
|
2013-09-08 08:23:01 -07:00
|
|
|
|
2015-12-11 03:37:40 -08:00
|
|
|
def verify_headers(self, header, prev_header, bits, target):
|
|
|
|
prev_hash = self.hash_header(prev_header)
|
|
|
|
assert prev_hash == header.get('prev_block_hash'), "prev hash mismatch: %s vs %s"% (prev_hash, header.get('prev_block_hash'))
|
|
|
|
assert bits == header.get('bits'), "bits mismatch: %s vs %s" % (bits, header.get('bits'))
|
|
|
|
_hash = self.hash_header(header)
|
|
|
|
assert int('0x'+_hash, 16) <= target, "insufficient proof of work: %s vs target %s" % (int('0x'+_hash, 16), target)
|
|
|
|
|
2013-09-02 08:49:12 -07:00
|
|
|
def verify_chain(self, chain):
|
|
|
|
first_header = chain[0]
|
|
|
|
prev_header = self.read_header(first_header.get('block_height') -1)
|
|
|
|
for header in chain:
|
|
|
|
height = header.get('block_height')
|
2015-12-11 03:37:40 -08:00
|
|
|
bits, target = self.get_target(height/2016, chain)
|
|
|
|
self.verify_headers(header, prev_header, bits, target)
|
2013-09-02 08:49:12 -07:00
|
|
|
prev_header = header
|
|
|
|
|
2013-09-01 09:16:15 -07:00
|
|
|
def verify_chunk(self, index, hexdata):
|
|
|
|
data = hexdata.decode('hex')
|
|
|
|
num = len(data)/80
|
2015-12-11 03:37:40 -08:00
|
|
|
prev_header = None if index == 0 else 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):
|
|
|
|
raw_header = data[i*80:(i+1)*80]
|
2015-12-11 03:37:40 -08:00
|
|
|
header = self.deserialize_header(raw_header)
|
|
|
|
self.verify_headers(header, prev_header, bits, target)
|
|
|
|
prev_header = header
|
2013-09-01 09:16:15 -07:00
|
|
|
self.save_chunk(index, data)
|
2015-12-11 03:37:40 -08:00
|
|
|
self.print_error("validated chunk %d" % index)
|
2014-10-21 10:05:51 -07:00
|
|
|
|
2015-12-11 03:37:40 -08:00
|
|
|
def serialize_header(self, res):
|
2013-09-01 09:16:15 -07:00
|
|
|
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
|
|
|
|
|
2015-12-11 03:37:40 -08:00
|
|
|
def deserialize_header(self, s):
|
2013-11-12 01:14:29 -08:00
|
|
|
hex_to_int = lambda s: int('0x' + s[::-1].encode('hex'), 16)
|
2013-09-01 09:16:15 -07:00
|
|
|
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])
|
|
|
|
return h
|
|
|
|
|
|
|
|
def hash_header(self, header):
|
2015-12-11 03:37:40 -08:00
|
|
|
return "0"*64 if header is None else rev_hex(Hash(self.serialize_header(header).decode('hex')).encode('hex'))
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
def path(self):
|
2015-05-08 04:43:42 -07:00
|
|
|
return os.path.join(self.config.path, 'blockchain_headers')
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
def init_headers_file(self):
|
|
|
|
filename = self.path()
|
|
|
|
if os.path.exists(filename):
|
|
|
|
return
|
|
|
|
try:
|
|
|
|
import urllib, socket
|
|
|
|
socket.setdefaulttimeout(30)
|
2015-03-25 01:22:27 -07:00
|
|
|
self.print_error("downloading ", self.headers_url )
|
2013-09-01 09:16:15 -07:00
|
|
|
urllib.urlretrieve(self.headers_url, filename)
|
2015-03-25 01:22:27 -07:00
|
|
|
self.print_error("done.")
|
2013-11-09 21:23:57 -08:00
|
|
|
except Exception:
|
2015-03-25 01:22:27 -07:00
|
|
|
self.print_error( "download failed. creating file", filename )
|
2013-09-01 09:16:15 -07:00
|
|
|
open(filename,'wb+').close()
|
|
|
|
|
|
|
|
def save_chunk(self, index, chunk):
|
|
|
|
filename = self.path()
|
|
|
|
f = open(filename,'rb+')
|
|
|
|
f.seek(index*2016*80)
|
|
|
|
h = f.write(chunk)
|
|
|
|
f.close()
|
2015-05-08 04:43:42 -07:00
|
|
|
self.set_local_height()
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
def save_header(self, header):
|
2015-12-11 03:37:40 -08:00
|
|
|
data = self.serialize_header(header).decode('hex')
|
2013-09-01 09:16:15 -07:00
|
|
|
assert len(data) == 80
|
|
|
|
height = header.get('block_height')
|
|
|
|
filename = self.path()
|
|
|
|
f = open(filename,'rb+')
|
|
|
|
f.seek(height*80)
|
|
|
|
h = f.write(data)
|
|
|
|
f.close()
|
2015-05-08 04:43:42 -07:00
|
|
|
self.set_local_height()
|
|
|
|
|
|
|
|
def set_local_height(self):
|
|
|
|
name = self.path()
|
|
|
|
if os.path.exists(name):
|
|
|
|
h = os.path.getsize(name)/80 - 1
|
|
|
|
if self.local_height != h:
|
|
|
|
self.local_height = h
|
2013-09-01 09:16:15 -07:00
|
|
|
|
|
|
|
def read_header(self, block_height):
|
|
|
|
name = self.path()
|
|
|
|
if os.path.exists(name):
|
|
|
|
f = open(name,'rb')
|
|
|
|
f.seek(block_height*80)
|
|
|
|
h = f.read(80)
|
|
|
|
f.close()
|
|
|
|
if len(h) == 80:
|
2015-12-11 03:37:40 -08:00
|
|
|
h = self.deserialize_header(h)
|
2014-10-21 10:05:51 -07:00
|
|
|
return h
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2014-06-25 08:43:45 -07:00
|
|
|
def get_target(self, index, chain=None):
|
2015-12-11 03:37:40 -08:00
|
|
|
if index == 0:
|
|
|
|
return 0x1d00ffff, MAX_TARGET
|
2013-09-01 09:16:15 -07: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:
|
|
|
|
if h.get('block_height') == index*2016-1:
|
|
|
|
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
|
|
|
|
assert bitsN >= 0x03 and bitsN <= 0x1d, "First part of bits should be in [0x03, 0x1d]"
|
|
|
|
bitsBase = bits & 0xffffff
|
2015-12-11 01:14:01 -08:00
|
|
|
assert bitsBase >= 0x8000 and bitsBase <= 0x7fffff, "Second part of bits should be in [0x8000, 0x7fffff]"
|
2015-11-19 09:43:57 -08:00
|
|
|
target = bitsBase << (8*(bitsN-3))
|
|
|
|
# new target
|
2013-09-01 09:16:15 -07:00
|
|
|
nActualTimespan = last.get('timestamp') - first.get('timestamp')
|
|
|
|
nTargetTimespan = 14*24*60*60
|
|
|
|
nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
|
|
|
|
nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
|
2015-12-11 03:37:40 -08:00
|
|
|
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-11-19 09:43:57 -08:00
|
|
|
bitsN, bitsBase = len(c)/2, int('0x'+c[:6], 16)
|
|
|
|
if bitsBase >= 0x800000:
|
|
|
|
bitsN += 1
|
|
|
|
bitsBase >>= 8
|
|
|
|
new_bits = bitsN << 24 | bitsBase
|
|
|
|
return new_bits, bitsBase << (8*(bitsN-3))
|
2013-09-01 09:16:15 -07:00
|
|
|
|
2015-05-17 06:54:20 -07:00
|
|
|
def connect_header(self, chain, header):
|
|
|
|
'''Builds a header chain until it connects. Returns True if it has
|
|
|
|
successfully connected, False if verification failed, otherwise the
|
|
|
|
height of the next header needed.'''
|
|
|
|
chain.append(header) # Ordered by decreasing height
|
|
|
|
previous_height = header['block_height'] - 1
|
|
|
|
previous_header = self.read_header(previous_height)
|
|
|
|
|
|
|
|
# Missing header, request it
|
|
|
|
if not previous_header:
|
|
|
|
return previous_height
|
|
|
|
|
|
|
|
# Does it connect to my chain?
|
|
|
|
prev_hash = self.hash_header(previous_header)
|
|
|
|
if prev_hash != header.get('prev_block_hash'):
|
|
|
|
self.print_error("reorg")
|
|
|
|
return previous_height
|
|
|
|
|
|
|
|
# The chain is complete. Reverse to order by increasing height
|
|
|
|
chain.reverse()
|
2015-12-11 03:37:40 -08:00
|
|
|
try:
|
|
|
|
self.verify_chain(chain)
|
2015-05-17 06:54:20 -07:00
|
|
|
self.print_error("connected at height:", previous_height)
|
|
|
|
for header in chain:
|
|
|
|
self.save_header(header)
|
|
|
|
return True
|
2015-12-11 03:37:40 -08:00
|
|
|
except BaseException as e:
|
|
|
|
self.print_error(str(e))
|
|
|
|
return False
|
2015-05-17 06:54:20 -07:00
|
|
|
|
|
|
|
def connect_chunk(self, idx, chunk):
|
|
|
|
try:
|
|
|
|
self.verify_chunk(idx, chunk)
|
|
|
|
return idx + 1
|
2015-12-11 03:37:40 -08:00
|
|
|
except BaseException as e:
|
|
|
|
self.print_error('verify_chunk failed', str(e))
|
2015-05-17 06:54:20 -07:00
|
|
|
return idx - 1
|