forked from alecalve/python-bitcoin-blockchain-parser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
61 lines (45 loc) · 1.43 KB
/
utils.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
# Copyright (C) 2015-2016 The bitcoin-blockchain-parser developers
#
# This file is part of bitcoin-blockchain-parser.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of bitcoin-blockchain-parser, including this file, may be copied,
# modified, propagated, or distributed except according to the terms contained
# in the LICENSE file.
from binascii import hexlify
import hashlib
import struct
def btc_ripemd160(data):
h1 = hashlib.sha256(data).digest()
r160 = hashlib.new("ripemd160")
r160.update(h1)
return r160.digest()
def double_sha256(data):
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def format_hash(hash_):
return str(hexlify(hash_[::-1]).decode("utf-8"))
def decode_uint32(data):
assert(len(data) == 4)
return struct.unpack("<I", data)[0]
def decode_uint64(data):
assert(len(data) == 8)
return struct.unpack("<Q", data)[0]
def decode_varint(data):
assert(len(data) > 0)
size = int(data[0])
assert(size <= 255)
if size < 253:
return size, 1
if size == 253:
format_ = '<H'
elif size == 254:
format_ = '<I'
elif size == 255:
format_ = '<Q'
else:
# Should never be reached
assert 0, "unknown format_ for size : %s" % size
size = struct.calcsize(format_)
return struct.unpack(format_, data[1:size+1])[0], size + 1