-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
unsignedtransactions.py
286 lines (249 loc) · 9.85 KB
/
unsignedtransactions.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import bytes, str, int
from beemgraphenebase.py23 import py23_bytes, bytes_types
import ecdsa
import hashlib
from binascii import hexlify, unhexlify
from collections import OrderedDict
from asn1crypto.core import OctetString
import struct
from future.utils import python_2_unicode_compatible
from collections import OrderedDict
import json
from .py23 import py23_bytes, bytes_types, integer_types, string_types, py23_chr
from .objecttypes import object_type
from .bip32 import parse_path
from .account import PublicKey
from .types import (
Array,
Set,
Signature,
PointInTime,
Uint16,
Uint32,
JsonObj,
String,
Varint32,
Optional
)
from .objects import GrapheneObject, isArgsThisClass
from .operations import Operation
from .chains import known_chains
from .ecdsasig import sign_message, verify_message
import logging
log = logging.getLogger(__name__)
try:
import secp256k1prp as secp256k1
USE_SECP256K1 = True
log.debug("Loaded secp256k1prp binding.")
except:
try:
import secp256k1
USE_SECP256K1 = True
log.debug("Loaded secp256k1 binding.")
except Exception:
USE_SECP256K1 = False
log.debug("To speed up transactions signing install \n"
" pip install secp256k1\n"
"or pip install secp256k1prp")
@python_2_unicode_compatible
class GrapheneObjectASN1(object):
""" Core abstraction class
This class is used for any JSON reflected object in Graphene.
* ``instance.__json__()``: encodes data into json format
* ``bytes(instance)``: encodes data into wire format
* ``str(instances)``: dumps json object as string
"""
def __init__(self, data=None):
self.data = data
def __bytes__(self):
if self.data is None:
return py23_bytes()
b = b""
output = b""
for name, value in list(self.data.items()):
if name == "operations":
for operation in value:
if isinstance(value, string_types):
b = py23_bytes(operation, 'utf-8')
else:
b = py23_bytes(operation)
output += OctetString(b).dump()
elif name != "signatures":
if isinstance(value, string_types):
b = py23_bytes(value, 'utf-8')
else:
b = py23_bytes(value)
output += OctetString(b).dump()
return output
def __json__(self):
if self.data is None:
return {}
d = {} # JSON output is *not* ordered
for name, value in list(self.data.items()):
if isinstance(value, Optional) and value.isempty():
continue
if isinstance(value, String):
d.update({name: str(value)})
else:
try:
d.update({name: JsonObj(value)})
except Exception:
d.update({name: value.__str__()})
return d
def __str__(self):
return json.dumps(self.__json__())
def toJson(self):
return self.__json__()
def json(self):
return self.__json__()
class Unsigned_Transaction(GrapheneObjectASN1):
""" Create an unsigned transaction with ASN1 encoder for using it with ledger
:param num ref_block_num:
:param num ref_block_prefix:
:param str expiration: expiration date
:param array operations: array of operations
"""
def __init__(self, *args, **kwargs):
if isArgsThisClass(self, args):
self.data = args[0].data
else:
if len(args) == 1 and len(kwargs) == 0:
kwargs = args[0]
prefix = kwargs.pop("prefix", "STM")
if "extensions" not in kwargs:
kwargs["extensions"] = Set([])
elif not kwargs.get("extensions"):
kwargs["extensions"] = Set([])
if "signatures" not in kwargs:
kwargs["signatures"] = Array([])
else:
kwargs["signatures"] = Array([Signature(unhexlify(a)) for a in kwargs["signatures"]])
operations_count = 0
if "operations" in kwargs:
operations_count = len(kwargs["operations"])
#opklass = self.getOperationKlass()
#if all([not isinstance(a, opklass) for a in kwargs["operations"]]):
# kwargs['operations'] = Array([opklass(a, prefix=prefix) for a in kwargs["operations"]])
#else:
# kwargs['operations'] = (kwargs["operations"])
super(Unsigned_Transaction, self).__init__(OrderedDict([
('ref_block_num', Uint16(kwargs['ref_block_num'])),
('ref_block_prefix', Uint32(kwargs['ref_block_prefix'])),
('expiration', PointInTime(kwargs['expiration'])),
('operations_count', Varint32(operations_count)),
('operations', kwargs['operations']),
('extensions', kwargs['extensions']),
('signatures', kwargs['signatures']),
]))
@property
def id(self):
""" The transaction id of this transaction
"""
# Store signatures temporarily since they are not part of
# transaction id
sigs = self.data["signatures"]
self.data.pop("signatures", None)
# Generage Hash of the seriliazed version
h = hashlib.sha256(py23_bytes(self)).digest()
# recover signatures
self.data["signatures"] = sigs
# Return properly truncated tx hash
return hexlify(h[:20]).decode("ascii")
def getOperationKlass(self):
return Operation
def derSigToHexSig(self, s):
""" Format DER to HEX signature
"""
s, junk = ecdsa.der.remove_sequence(unhexlify(s))
if junk:
log.debug('JUNK: %s', hexlify(junk).decode('ascii'))
if not (junk == b''):
raise AssertionError()
x, s = ecdsa.der.remove_integer(s)
y, s = ecdsa.der.remove_integer(s)
return '%064x%064x' % (x, y)
def getKnownChains(self):
return known_chains
def getChainParams(self, chain):
# Which network are we on:
chains = self.getKnownChains()
if isinstance(chain, str) and chain in chains:
chain_params = chains[chain]
elif isinstance(chain, dict):
chain_params = chain
else:
raise Exception("sign() only takes a string or a dict as chain!")
if "chain_id" not in chain_params:
raise Exception("sign() needs a 'chain_id' in chain params!")
return chain_params
def deriveDigest(self, chain):
chain_params = self.getChainParams(chain)
# Chain ID
self.chainid = chain_params["chain_id"]
# Do not serialize signatures
sigs = self.data["signatures"]
self.data["signatures"] = []
# Get message to sign
# bytes(self) will give the wire formated data according to
# GrapheneObject and the data given in __init__()
self.message = OctetString(unhexlify(self.chainid)).dump()
for name, value in list(self.data.items()):
if name == "operations":
for operation in value:
if isinstance(value, string_types):
b = py23_bytes(operation, 'utf-8')
else:
b = py23_bytes(operation)
self.message += OctetString(b).dump()
elif name != "signatures":
if isinstance(value, string_types):
b = py23_bytes(value, 'utf-8')
else:
b = py23_bytes(value)
self.message += OctetString(b).dump()
self.digest = hashlib.sha256(self.message).digest()
# restore signatures
self.data["signatures"] = sigs
def build_path(self, role, account_index, key_index):
if role == "owner":
return "48'/13'/0'/%d'/%d'" % (account_index, key_index)
elif role == "active":
return "48'/13'/1'/%d'/%d'" % (account_index, key_index)
elif role == "posting":
return "48'/13'/4'/%d'/%d'" % (account_index, key_index)
elif role == "memo":
return "48'/13'/3'/%d'/%d'" % (account_index, key_index)
def build_apdu(self, path="48'/13'/0'/0'/0'", chain=None):
self.deriveDigest(chain)
path = unhexlify(parse_path(path, as_bytes=True))
message = self.message
path_size = int(len(path) / 4)
message_size = len(message)
offset = 0
first = True
result = []
while offset != message_size:
if message_size - offset > 200:
chunk = message[offset: offset + 200]
else:
chunk = message[offset:]
if first:
total_size = int(len(path)) + 1 + len(chunk)
apdu = unhexlify("d4040000") + py23_chr(total_size) + py23_chr(path_size) + path + chunk
first = False
else:
total_size = len(chunk)
apdu = unhexlify("d4048000") + py23_chr(total_size) + chunk
result.append(apdu)
offset += len(chunk)
return result
def build_apdu_pubkey(self, path="48'/13'/0'/0'/0'", request_screen_approval=False):
path = unhexlify(parse_path(path, as_bytes=True))
if not request_screen_approval:
return unhexlify("d4020001") + py23_chr(int(len(path)) + 1) + py23_chr(int(len(path) / 4)) + path
else:
return unhexlify("d4020101") + py23_chr(int(len(path)) + 1) + py23_chr(int(len(path) / 4)) + path