forked from bitshares/python-bitshares
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.py
More file actions
181 lines (145 loc) · 5.89 KB
/
message.py
File metadata and controls
181 lines (145 loc) · 5.89 KB
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
import json
import logging
import re
from binascii import hexlify, unhexlify
from bitsharesbase.account import PublicKey
from graphenebase.ecdsa import sign_message, verify_message
from .account import Account
from .exceptions import (
AccountDoesNotExistsException,
InvalidMemoKeyException,
InvalidMessageSignature,
WrongMemoKey,
)
from .instance import BlockchainInstance
log = logging.getLogger(__name__)
MESSAGE_SPLIT = (
"-----BEGIN BITSHARES SIGNED MESSAGE-----",
"-----BEGIN META-----",
"-----BEGIN SIGNATURE-----",
"-----END BITSHARES SIGNED MESSAGE-----",
)
# This is the message that is actually signed
SIGNED_MESSAGE_META = """{message}
account={meta[account]}
memokey={meta[memokey]}
block={meta[block]}
timestamp={meta[timestamp]}"""
SIGNED_MESSAGE_ENCAPSULATED = """
{MESSAGE_SPLIT[0]}
{message}
{MESSAGE_SPLIT[1]}
account={meta[account]}
memokey={meta[memokey]}
block={meta[block]}
timestamp={meta[timestamp]}
{MESSAGE_SPLIT[2]}
{signature}
{MESSAGE_SPLIT[3]}
"""
class Message(BlockchainInstance):
def __init__(self, message, *args, **kwargs):
BlockchainInstance.__init__(self, *args, **kwargs)
self.message = message.replace("\r\n", "\n")
self.signed_by_account = None
self.signed_by_name = None
self.meta = None
self.plain_message = None
def sign(self, account=None, **kwargs):
""" Sign a message with an account's memo key
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
:raises ValueError: If not account for signing is provided
:returns: the signed message encapsulated in a known format
"""
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
# Data for message
account = Account(account, blockchain_instance=self.blockchain)
info = self.blockchain.info()
meta = dict(
timestamp=info["time"],
block=info["head_block_number"],
memokey=account["options"]["memo_key"],
account=account["name"],
)
# wif key
wif = self.blockchain.wallet.getPrivateKeyForPublicKey(
account["options"]["memo_key"]
)
# We strip the message here so we know for sure there are no trailing
# whitespaces or returns
message = self.message.strip()
enc_message = SIGNED_MESSAGE_META.format(**locals())
# signature
signature = hexlify(sign_message(enc_message, wif)).decode("ascii")
self.signed_by_account = account
self.signed_by_name = account["name"]
self.meta = meta
self.plain_message = message
return SIGNED_MESSAGE_ENCAPSULATED.format(
MESSAGE_SPLIT=MESSAGE_SPLIT, **locals()
)
def verify(self, **kwargs):
""" Verify a message with an account's memo key
:param str account: (optional) the account that owns the bet
(defaults to ``default_account``)
:returns: True if the message is verified successfully
:raises InvalidMessageSignature if the signature is not ok
"""
# Split message into its parts
parts = re.split("|".join(MESSAGE_SPLIT), self.message)
parts = [x for x in parts if x.strip()]
assert len(parts) > 2, "Incorrect number of message parts"
# Strip away all whitespaces before and after the message
message = parts[0].strip()
signature = parts[2].strip()
# Parse the meta data
meta = dict(re.findall(r"(\S+)=(.*)", parts[1]))
log.info("Message is: {}".format(message))
log.info("Meta is: {}".format(json.dumps(meta)))
log.info("Signature is: {}".format(signature))
# Ensure we have all the data in meta
assert "account" in meta, "No 'account' could be found in meta data"
assert "memokey" in meta, "No 'memokey' could be found in meta data"
assert "block" in meta, "No 'block' could be found in meta data"
assert "timestamp" in meta, "No 'timestamp' could be found in meta data"
account_name = meta.get("account").strip()
memo_key = meta["memokey"].strip()
try:
PublicKey(memo_key, prefix=self.blockchain.prefix)
except Exception:
raise InvalidMemoKeyException("The memo key in the message is invalid")
# Load account from blockchain
try:
account = Account(account_name, blockchain_instance=self.blockchain)
except AccountDoesNotExistsException:
raise AccountDoesNotExistsException(
"Could not find account {}. Are you connected to the right chain?".format(
account_name
)
)
# Test if memo key is the same as on the blockchain
if not account["options"]["memo_key"] == memo_key:
raise WrongMemoKey(
"Memo Key of account {} on the Blockchain ".format(account["name"])
+ "differs from memo key in the message: {} != {}".format(
account["options"]["memo_key"], memo_key
)
)
# Reformat message
enc_message = SIGNED_MESSAGE_META.format(**locals())
# Verify Signature
pubkey = verify_message(enc_message, unhexlify(signature))
# Verify pubky
pk = PublicKey(hexlify(pubkey).decode("ascii"), prefix=self.blockchain.prefix)
if format(pk, self.blockchain.prefix) != memo_key:
raise InvalidMessageSignature("The signature doesn't match the memo key")
self.signed_by_account = account
self.signed_by_name = account["name"]
self.meta = meta
self.plain_message = message
return True