forked from ohac/electrum
/
blockchain.py
594 lines (504 loc) · 21.5 KB
/
blockchain.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@ecdsa.org
#
# 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:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# 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
import threading
from . import util
from . import bitcoin
from .bitcoin import *
try:
import lyra2re2_hash
except ImportError as e:
exit("Please run 'sudo pip3 install https://github.com/metalicjames/lyra2re-hash-python/archive/master.zip'")
try:
import ltc_scrypt
except ImportError as e:
exit("Please run 'sudo pip3 install https://github.com/wakiyamap/ltc-scrypt/archive/master.zip'")
MAX_TARGET = 0x00000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
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' + 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['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(bfh(serialize_header(header))))
blockchains = {}
def read_blockchains(config):
blockchains[0] = Blockchain(config, 0, None)
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]))
for filename in l:
checkpoint = int(filename.split('_')[2])
parent_id = int(filename.split('_')[1])
b = Blockchain(config, checkpoint, parent_id)
blockchains[b.checkpoint] = b
return blockchains
def check_header(header):
if type(header) is not dict:
return False
for b in blockchains.values():
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):
"""
Manages blockchain headers and their verification
"""
def __init__(self, config, checkpoint, parent_id):
self.config = config
self.catch_up = None # interface catching up
self.checkpoint = checkpoint
self.parent_id = parent_id
self.lock = threading.Lock()
with self.lock:
self.update_size()
def parent(self):
return blockchains[self.parent_id]
def get_max_child(self):
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]
def check_header(self, header):
header_hash = hash_header(header)
height = header.get('block_height')
return header_hash == self.get_hash(height)
def fork(parent, header):
checkpoint = header.get('block_height')
self = Blockchain(parent.config, checkpoint, parent.checkpoint)
open(self.path(), 'w+').close()
self.save_header(header)
return self
def height(self):
return self.checkpoint + self.size() - 1
def size(self):
with self.lock:
return self._size
def update_size(self):
p = self.path()
self._size = os.path.getsize(p)//80 if os.path.exists(p) else 0
def verify_header(self, header, prev_header, bits, target):
prev_hash = hash_header(prev_header)
height = header.get('block_height')
if height < 450000 :
_powhash = rev_hex(bh2u(ltc_scrypt.getPoWHash(bfh(serialize_header(header)))))
else:
_powhash = rev_hex(bh2u(lyra2re2_hash.getPoWHash(bfh(serialize_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.TESTNET:
return
if bits != header.get('bits'):
raise BaseException("bits mismatch: %s vs %s" % (bits, header.get('bits')))
if int('0x' + _powhash, 16) > target:
raise BaseException("insufficient proof of work: %s vs target %s" % (int('0x' + _powhash, 16), target))
def verify_chunk(self, index, data):
num = len(data) // 80
prev_header = None
if index != 0:
prev_header = self.read_header(index * 2016 - 1)
headers = {}
for i in range(num):
raw_header = data[i*80:(i+1) * 80]
header = deserialize_header(raw_header, index*2016 + i)
headers[header.get('block_height')] = header
bits, target = self.get_target(index*2016 + i, headers)
self.verify_header(header, prev_header, bits, target)
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))
return os.path.join(d, filename)
def save_chunk(self, index, chunk):
filename = self.path()
d = (index * 2016 - self.checkpoint) * 80
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)*80)
parent_data = f.read(parent_branch_size*80)
self.write(parent_data, 0)
parent.write(my_data, (checkpoint - parent.checkpoint)*80)
# store file path
for b in blockchains.values():
b.old_path = b.path()
# 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())
# update pointers
blockchains[self.checkpoint] = self
blockchains[parent.checkpoint] = parent
def write(self, data, offset):
filename = self.path()
with self.lock:
with open(filename, 'rb+') as f:
if offset != self._size*80:
f.seek(offset)
f.truncate()
f.seek(offset)
f.write(data)
f.flush()
os.fsync(f.fileno())
self.update_size()
def save_header(self, header):
delta = header.get('block_height') - self.checkpoint
data = bfh(serialize_header(header))
assert delta == self.size()
assert len(data) == 80
self.write(data, delta*80)
self.swap_with_parent()
def read_header(self, height):
assert self.parent_id != self.checkpoint
if height < 0:
return
if height < self.checkpoint:
return self.parent().read_header(height)
if height > self.height():
return
delta = height - self.checkpoint
name = self.path()
if os.path.exists(name):
f = open(name, 'rb')
f.seek(delta * 80)
h = f.read(80)
f.close()
return deserialize_header(h, height)
def get_hash(self, height):
return hash_header(self.read_header(height))
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.
def bits_to_target(self, bits):
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(self, target):
MM = 256*256*256
c = ("%064X"%int(target))[2:]
i = 31
while c[0:2]=="00":
c = c[2:]
i -= 1
c = int('0x'+c[0:6],16)
if c >= 0x800000:
c //= 256
i += 1
new_bits = c + MM * i
return new_bits
def convbits(self, new_target):
c = ("%064x" % int(new_target))[2:]
while c[:2] == '00' and len(c) > 6:
c = c[2:]
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
def convbignum(self, bits):
bitsN = (bits >> 24) & 0xff
if not (bitsN >= 0x03 and bitsN <= 0x1e):
raise BaseException("First part of bits should be in [0x03, 0x1e]")
bitsBase = bits & 0xffffff
if not (bitsBase >= 0x8000 and bitsBase <= 0x7fffff):
raise BaseException("Second part of bits should be in [0x8000, 0x7fffff]")
target = bitsBase << (8 * (bitsN-3))
return target
def get_target_ltc(self, height, chain=None):
if height < 1056:
return 0x1e0ffff0, MAX_TARGET
# Litecoin: go back the full period unless it's the first retarget
first = self.read_header(height - 1056 - 1 if height > 1056 else 0)
if first is None:
first = chain.get(height - 1056 - 1 if height > 1056 else 0)
last = self.read_header(height - 1)
if last is None:
last = chain.get(height - 1)
assert last is not None
# bits to target
bits = last.get('bits')
bitsN = (bits >> 24) & 0xff
if not (bitsN >= 0x03 and bitsN <= 0x1e):
raise BaseException("First part of bits should be in [0x03, 0x1e]")
bitsBase = bits & 0xffffff
if not (bitsBase >= 0x8000 and bitsBase <= 0x7fffff):
raise BaseException("Second part of bits should be in [0x8000, 0x7fffff]")
target = bitsBase << (8 * (bitsN-3))
if height % 1056 != 0:
return bits, target
# new target
nActualTimespan = last.get('timestamp') - first.get('timestamp')
nTargetTimespan = 95040; #1.1 days 1.1*24*60*60
nActualTimespan = max(nActualTimespan, nTargetTimespan // 4)
nActualTimespan = min(nActualTimespan, nTargetTimespan * 4)
new_target = min(MAX_TARGET, (target*nActualTimespan) // nTargetTimespan)
# convert new target to bits
c = ("%064x" % int(new_target))[2:]
while c[:2] == '00' and len(c) > 6:
c = c[2:]
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))
def get_target_kgw(self, height, chain={}): #from vertcoin thanks https://github.com/vertcoin/electrum-vtc
BlocksTargetSpacing = 1.5 * 60; # 1.5 minutes
TimeDaySeconds = 60 * 60 * 24;
PastSecondsMin = TimeDaySeconds * 0.25;
PastSecondsMax = TimeDaySeconds * 7;
PastBlocksMin = PastSecondsMin // BlocksTargetSpacing;
PastBlocksMax = PastSecondsMax // BlocksTargetSpacing;
BlockReadingIndex = height - 1
BlockLastSolvedIndex = height - 1
TargetBlocksSpacingSeconds = BlocksTargetSpacing
PastRateAdjustmentRatio = 1.0
bnProofOfWorkLimit = MAX_TARGET
if (BlockLastSolvedIndex<=0 or BlockLastSolvedIndex<PastSecondsMin):
new_target = bnProofOfWorkLimit
new_bits = self.convbits(new_target)
return new_bits, new_target
last = chain.get(BlockLastSolvedIndex)
if last == None:
last = self.read_header(BlockLastSolvedIndex)
for i in range(1,int(PastBlocksMax)+1):
PastBlocksMass=i
reading = chain.get(BlockReadingIndex)
if reading == None:
reading = self.read_header(BlockReadingIndex)
chain[BlockReadingIndex] = reading
if (reading == None or last == None):
raise BaseException("Could not find previous blocks when calculating difficulty reading: " + str(BlockReadingIndex) + ", last: " + str(BlockLastSolvedIndex) + ", height: " + str(height))
if (i == 1):
PastDifficultyAverage=self.convbignum(reading.get('bits'))
else:
PastDifficultyAverage= float((self.convbignum(reading.get('bits')) - PastDifficultyAveragePrev) / float(i)) + PastDifficultyAveragePrev;
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = last.get('timestamp') - reading.get('timestamp');
PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;
PastRateAdjustmentRatio = 1.0
if (PastRateActualSeconds < 0):
PastRateActualSeconds = 0.0
if (PastRateActualSeconds != 0 and PastRateTargetSeconds != 0):
PastRateAdjustmentRatio = float(PastRateTargetSeconds) / float(PastRateActualSeconds)
EventHorizonDeviation = 1 + (0.7084 * pow(float(PastBlocksMass)/float(144), -1.228))
EventHorizonDeviationFast = EventHorizonDeviation
EventHorizonDeviationSlow = float(1) / float(EventHorizonDeviation)
if (PastBlocksMass >= PastBlocksMin):
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) or (PastRateAdjustmentRatio >= EventHorizonDeviationFast)):
break;
if (BlockReadingIndex<1):
break
BlockReadingIndex = BlockReadingIndex -1;
bnNew = PastDifficultyAverage
if (PastRateActualSeconds != 0 and PastRateTargetSeconds != 0):
bnNew *= float(PastRateActualSeconds);
bnNew //= float(PastRateTargetSeconds);
if (bnNew > bnProofOfWorkLimit):
bnNew = bnProofOfWorkLimit
# new target
new_target = bnNew
new_bits = self.convbits(new_target)
return new_bits, new_target
def get_target_dgsld(self, height, chain=None):
if chain is None:
chain = {}
nPowTargetTimespan = 95040 #1.1 days 1.1*24*60*60
nPowTargetSpacing = 90 #1.5 minute
nPowTargetSpacingDigisheld = 90 #1.5 minute
DifficultyAdjustmentIntervalDigisheld = nPowTargetSpacingDigisheld // nPowTargetSpacing #1
AdjustmentInterval = DifficultyAdjustmentIntervalDigisheld
blockstogoback = AdjustmentInterval - 1
if (height != AdjustmentInterval):
blockstogoback = AdjustmentInterval
last_height = height - 1
first_height = last_height - blockstogoback
TargetTimespan = nPowTargetSpacingDigisheld
first = chain.get(first_height)
if first is None:
first = self.read_header(first_height)
last = chain.get(last_height)
if last is None:
last = self.read_header(last_height)
nActualTimespan = last.get('timestamp') - first.get('timestamp')
nActualTimespan = TargetTimespan + int(float(nActualTimespan - TargetTimespan) / float(8))
nActualTimespan = max(nActualTimespan, TargetTimespan - int(float(TargetTimespan) / float(4)))
nActualTimespan = min(nActualTimespan, TargetTimespan + int(float(TargetTimespan) / float(2)))
bits = last.get('bits')
bnNew = self.bits_to_target(bits)
if height % AdjustmentInterval != 0:
return bits, bnNew
# retarget
bnNew *= nActualTimespan
bnNew //= TargetTimespan
bnNew = min(bnNew, MAX_TARGET)
new_bits = self.target_to_bits(bnNew)
return new_bits, bnNew
def get_target_dgwv3(self, height, chain=None):
if chain is None:
chain = {}
last = chain.get(height - 1)
if last is None:
last = self.read_header(height - 1)
# params
BlockLastSolved = last
BlockReading = last
BlockCreating = height
nActualTimespan = 0
LastBlockTime = 0
PastBlocksMin = 24
PastBlocksMax = 24
CountBlocks = 0
PastDifficultyAverage = 0
PastDifficultyAveragePrev = 0
bnNum = 0
#thanks watanabe!! http://askmona.org/5288#res_61
if BlockLastSolved is None or height-1 < 450024:
return 0x1e0fffff, MAX_TARGET
for i in range(1, PastBlocksMax + 1):
CountBlocks += 1
if CountBlocks <= PastBlocksMin:
if CountBlocks == 1:
PastDifficultyAverage = self.bits_to_target(BlockReading.get('bits'))
else:
bnNum = self.bits_to_target(BlockReading.get('bits'))
PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks)+(bnNum)) // (CountBlocks + 1)
PastDifficultyAveragePrev = PastDifficultyAverage
if LastBlockTime > 0:
Diff = (LastBlockTime - BlockReading.get('timestamp'))
nActualTimespan += Diff
LastBlockTime = BlockReading.get('timestamp')
BlockReading = chain.get((height-1) - CountBlocks)
if BlockReading is None:
BlockReading = self.read_header((height-1) - CountBlocks)
bnNew = PastDifficultyAverage
nTargetTimespan = CountBlocks * 90 #1.5 miniutes
nActualTimespan = max(nActualTimespan, nTargetTimespan//3)
nActualTimespan = min(nActualTimespan, nTargetTimespan*3)
# retarget
bnNew *= nActualTimespan
bnNew //= nTargetTimespan
bnNew = min(bnNew, MAX_TARGET)
new_bits = self.target_to_bits(bnNew)
return new_bits, bnNew
def get_target(self, height, chain=None):
if bitcoin.TESTNET:
return 0, 0
if height < 80000:
return self.get_target_ltc(height, chain)
if height < 140000:
return self.get_target_kgw(height, chain)
if height < 450000:
return self.get_target_dgsld(height, chain)
if height >= 450000:
return self.get_target_dgwv3(height, chain)
else:
return 0, 0
def can_connect(self, header, check_height=True):
height = header['block_height']
if check_height and self.height() != height - 1:
return False
if height == 0:
return hash_header(header) == bitcoin.GENESIS
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
headers = {}
headers[header.get('block_height')] = header
bits, target = self.get_target(height, headers)
try:
self.verify_header(header, previous_header, bits, target)
except:
return False
return True
def connect_chunk(self, idx, hexdata):
try:
data = bfh(hexdata)
self.verify_chunk(idx, data)
#self.print_error("validated chunk %d" % idx)
self.save_chunk(idx, data)
return True
except BaseException as e:
self.print_error('verify_chunk failed', str(e))
return False