forked from petertodd/python-bitcoinlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignmessage.py
60 lines (43 loc) · 1.83 KB
/
signmessage.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
# Copyright (C) 2013-2015 The python-bitcoinlib developers
#
# This file is part of python-bitcoinlib.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-bitcoinlib, including this file, may be copied, modified,
# propagated, or distributed except according to the terms contained in the
# LICENSE file.
from bitcoin.core.key import CPubKey
from bitcoin.core.serialize import ImmutableSerializable
from bitcoin.wallet import P2PKHBitcoinAddress
import bitcoin
import base64
def VerifyMessage(address, message, sig):
sig = base64.b64decode(sig)
hash = message.GetHash()
pubkey = CPubKey.recover_compact(hash, sig)
return str(P2PKHBitcoinAddress.from_pubkey(pubkey)) == str(address)
def SignMessage(key, message):
sig, i = key.sign_compact(message.GetHash())
meta = 27 + i
if key.is_compressed:
meta += 4
return base64.b64encode(bytes([meta]) + sig)
class BitcoinMessage(ImmutableSerializable):
__slots__ = ['magic', 'message']
def __init__(self, message="", magic="Bitcoin Signed Message:\n"):
object.__setattr__(self, 'message', message.encode("utf-8"))
object.__setattr__(self, 'magic', magic.encode("utf-8"))
@classmethod
def stream_deserialize(cls, f):
magic = bitcoin.core.serialize.BytesSerializer.stream_deserialize(f)
message = bitcoin.core.serialize.BytesSerializer.stream_deserialize(f)
return cls(message, magic)
def stream_serialize(self, f):
bitcoin.core.serialize.BytesSerializer.stream_serialize(self.magic, f)
bitcoin.core.serialize.BytesSerializer.stream_serialize(self.message, f)
def __str__(self):
return self.message.decode('ascii')
def __repr__(self):
return 'BitcoinMessage(%s, %s)' % (self.magic, self.message)