-
Notifications
You must be signed in to change notification settings - Fork 8
/
wtypes.py
532 lines (421 loc) · 16.6 KB
/
wtypes.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
import base64
import typing
from collections.abc import Callable, Iterable, Mapping, Sequence
import attrs
from immutabledict import immutabledict
from puya.algo_constants import (
ADDRESS_CHECKSUM_LENGTH,
ENCODED_ADDRESS_LENGTH,
MAX_BIGUINT_BITS,
MAX_BYTES_LENGTH,
PUBLIC_KEY_HASH_LENGTH,
)
from puya.awst_build import constants
from puya.errors import InternalError
from puya.utils import sha512_256_hash
def _all_literals_invalid(_value: object) -> bool:
return False
@attrs.frozen(str=False, kw_only=True)
class WType:
name: str
stub_name: str
lvalue: bool = True
immutable: bool = True
is_valid_literal: Callable[[object], bool] = attrs.field(
default=_all_literals_invalid,
eq=False, # TODO: is this the right thing to do?
)
def __str__(self) -> str:
return self.stub_name
def is_valid_bool_literal(value: object) -> typing.TypeGuard[bool]:
return isinstance(value, bool)
def _is_unsigned_int(value: object) -> typing.TypeGuard[int]:
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
def is_valid_uint64_literal(value: object) -> typing.TypeGuard[int]:
return _is_unsigned_int(value) and value.bit_length() <= 64
def is_valid_biguint_literal(value: object) -> typing.TypeGuard[int]:
return _is_unsigned_int(value) and value.bit_length() <= MAX_BIGUINT_BITS
def is_valid_bytes_literal(value: object) -> typing.TypeGuard[bytes]:
return isinstance(value, bytes) and len(value) <= MAX_BYTES_LENGTH
def is_valid_account_literal(value: object) -> typing.TypeGuard[str]:
return isinstance(value, str) and valid_address(value)
def is_valid_utf8_literal(value: object) -> typing.TypeGuard[str]:
return isinstance(value, str) and is_valid_bytes_literal(value.encode("utf8"))
void_wtype: typing.Final = WType(
name="void",
stub_name="None",
lvalue=False,
)
bool_wtype: typing.Final = WType(
name="bool",
stub_name="bool",
is_valid_literal=is_valid_bool_literal,
)
uint64_wtype: typing.Final = WType(
name="uint64",
stub_name=constants.CLS_UINT64_ALIAS,
is_valid_literal=is_valid_uint64_literal,
)
biguint_wtype: typing.Final = WType(
name="biguint",
stub_name=constants.CLS_BIGUINT_ALIAS,
is_valid_literal=is_valid_biguint_literal,
)
bytes_wtype: typing.Final = WType(
name="bytes",
stub_name=constants.CLS_BYTES_ALIAS,
is_valid_literal=is_valid_bytes_literal,
)
asset_wtype: typing.Final = WType(
name="asset",
stub_name=constants.CLS_ASSET_ALIAS,
is_valid_literal=is_valid_uint64_literal,
)
account_wtype: typing.Final = WType(
name="account",
stub_name=constants.CLS_ACCOUNT_ALIAS,
is_valid_literal=is_valid_account_literal,
)
application_wtype: typing.Final = WType(
name="application",
stub_name=constants.CLS_APPLICATION_ALIAS,
is_valid_literal=is_valid_uint64_literal,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class WGroupTransaction(WType):
transaction_type: constants.TransactionType | None
@classmethod
def from_type(cls, transaction_type: constants.TransactionType | None) -> "WGroupTransaction":
name = "group_transaction"
if transaction_type:
name = f"{name}_{transaction_type.name}"
return cls(
transaction_type=transaction_type,
stub_name=constants.TRANSACTION_TYPE_TO_CLS[transaction_type].gtxn,
name=name,
)
# TODO only allow int literals below max group size
@attrs.define
class WInnerTransactionFields(WType):
transaction_type: constants.TransactionType | None
@classmethod
def from_type(
cls, transaction_type: constants.TransactionType | None
) -> "WInnerTransactionFields":
name = "inner_transaction_fields"
if transaction_type:
name = f"{name}_{transaction_type.name}"
return cls(
transaction_type=transaction_type,
stub_name=constants.TRANSACTION_TYPE_TO_CLS[transaction_type].itxn_fields,
name=name,
)
@attrs.define
class WInnerTransaction(WType):
transaction_type: constants.TransactionType | None
@classmethod
def from_type(cls, transaction_type: constants.TransactionType | None) -> "WInnerTransaction":
name = "inner_transaction"
if transaction_type:
name = f"{name}_{transaction_type.name}"
return cls(
transaction_type=transaction_type,
stub_name=constants.TRANSACTION_TYPE_TO_CLS[transaction_type].itxn_result,
name=name,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class WStructType(WType):
fields: Mapping[str, WType] = attrs.field(converter=immutabledict)
@classmethod
def from_name_and_fields(cls, python_name: str, fields: Mapping[str, WType]) -> typing.Self:
if not fields:
raise ValueError("struct needs fields")
if void_wtype in fields.values():
raise ValueError("struct should not contain void types")
name = (
"struct<"
+ ",".join(
f"{field_name}:{field_type.name}" for field_name, field_type in fields.items()
)
+ ">"
)
return cls(
name=name,
stub_name=python_name,
immutable=False,
fields=fields,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class WArray(WType):
element_type: WType
@classmethod
def from_element_type(cls, element_type: WType) -> typing.Self:
if element_type == void_wtype:
raise ValueError("array element type cannot be void")
name = f"array<{element_type.name}>"
return cls(
name=name,
stub_name=f"{constants.CLS_ARRAY_ALIAS}[{element_type}]",
immutable=False,
element_type=element_type,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class WTuple(WType):
types: tuple[WType, ...] = attrs.field(validator=[attrs.validators.min_len(1)])
@classmethod
def from_types(cls, types: Iterable[WType]) -> typing.Self:
types = tuple(types)
if not types:
raise ValueError("tuple needs types")
if void_wtype in types:
raise ValueError("tuple should not contain void types")
name = f"tuple<{','.join([t.name for t in types])}>"
python_name = f"tuple[{', '.join(map(str, types))}]"
return cls(name=name, stub_name=python_name, types=types)
@attrs.frozen
class ARC4Type(WType):
alias: str | None = None
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4UIntN(ARC4Type):
n: int
@classmethod
def from_scale(cls, n: int, *, alias: str | None = None) -> typing.Self:
assert n % 8 == 0, "bit size must be multiple of 8"
assert 8 <= n <= 512, "bit size must be between 8 and 512 inclusive"
name = f"arc4.uint{n}"
base_cls = constants.CLS_ARC4_UINTN if n <= 64 else constants.CLS_ARC4_BIG_UINTN
def is_valid_literal(value: object) -> bool:
return isinstance(value, int) and value >= 0 and value.bit_length() <= n
return cls(
n=n,
name=name,
stub_name=f"{base_cls}[typing.Literal[{n}]]",
alias=alias,
is_valid_literal=is_valid_literal,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4Tuple(ARC4Type):
types: tuple[WType, ...] = attrs.field(validator=[attrs.validators.min_len(1)])
@classmethod
def from_types(cls, types: Iterable[WType]) -> typing.Self:
types = tuple(types)
if not types:
raise ValueError("arc4.Tuple needs types")
for typ in types:
if not is_arc4_encoded_type(typ):
raise ValueError(f"Invalid type for arc4.Tuple: {typ}")
name = f"arc4.tuple<{','.join([t.name for t in types])}>"
python_name = f"{constants.CLS_ARC4_TUPLE}[{', '.join(map(str, types))}]"
return cls(name=name, stub_name=python_name, types=types)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4UFixedNxM(ARC4Type):
n: int
m: int
@classmethod
def from_scale_and_precision(cls, n: int, m: int) -> typing.Self:
assert n % 8 == 0, "bit size must be multiple of 8"
assert 8 <= n <= 512, "bit size must be between 8 and 512 inclusive"
assert 1 <= m <= 160, "precision must be between 1 and 160 inclusive"
name = f"arc4.ufixed{n}x{m}"
base_cls = constants.CLS_ARC4_UFIXEDNXM if n <= 64 else constants.CLS_ARC4_BIG_UFIXEDNXM
def is_valid_literal(value: object) -> bool:
import decimal
if not isinstance(value, decimal.Decimal):
return False
if value < 0 or not value.is_finite():
return False
decimal_str = str(value)
try:
whole, part = decimal_str.split(".")
except ValueError:
return False
# note: input is expected to be quantized correctly already
if len(part) != m:
return False
adjusted_int = int(decimal_str.replace(".", ""))
return adjusted_int.bit_length() <= n
return cls(
n=n,
m=m,
name=name,
stub_name=f"{base_cls}[typing.Literal[{n}], typing.Literal[{m}]]",
is_valid_literal=is_valid_literal,
)
@attrs.frozen(str=False, kw_only=True)
class ARC4Array(ARC4Type):
element_type: WType
immutable: bool = attrs.field(default=False, init=False)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4DynamicArray(ARC4Array):
@classmethod
def from_element_type(cls, element_type: WType) -> typing.Self:
if not is_arc4_encoded_type(element_type):
raise ValueError(f"Invalid type for arc4.DynamicArray: {element_type}")
name = f"arc4.dynamic_array<{element_type.name}>"
return cls(
name=name,
element_type=element_type,
stub_name=f"{constants.CLS_ARC4_DYNAMIC_ARRAY}[{element_type}]",
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4StaticArray(ARC4Array):
array_size: int
@classmethod
def from_element_type_and_size(
cls, element_type: WType, array_size: int, alias: str | None = None
) -> typing.Self:
if not is_arc4_encoded_type(element_type):
raise ValueError(f"Invalid type for arc4.StaticArray: {element_type}")
name = f"arc4.static_array<{element_type.name}, {array_size}>"
return cls(
array_size=array_size,
name=name,
element_type=element_type,
stub_name=(
f"{constants.CLS_ARC4_STATIC_ARRAY}["
f"{element_type}, typing.Literal[{array_size}]"
f"]"
),
alias=alias,
)
@typing.final
@attrs.frozen(str=False, kw_only=True)
class ARC4Struct(ARC4Type):
fields: Mapping[str, WType] = attrs.field(
converter=immutabledict, validator=[attrs.validators.min_len(1)]
)
names: Sequence[str] = attrs.field(init=False, eq=False)
types: Sequence[WType] = attrs.field(init=False, eq=False)
immutable: bool = attrs.field(default=False, init=False)
@names.default
def _names_factory(self) -> Sequence[str]:
return list(self.fields.keys())
@types.default
def _types_factory(self) -> Sequence[WType]:
return list(self.fields.values())
@classmethod
def from_name_and_fields(cls, *, python_name: str, fields: Mapping[str, WType]) -> typing.Self:
if not fields:
raise ValueError("arc4.Struct needs at least one element")
for t in fields.values():
if not is_arc4_encoded_type(t):
raise ValueError(f"arc4.Struct should not contain non arc4 types: {t}")
name = (
"arc4.struct<"
+ ",".join(
f"{field_name}:{field_type.name}" for field_name, field_type in fields.items()
)
+ ">"
)
return cls(name=name, stub_name=python_name, fields=fields)
arc4_string_wtype: typing.Final = ARC4Type(
name="arc4.string",
stub_name=constants.CLS_ARC4_STRING,
alias="string",
is_valid_literal=is_valid_utf8_literal,
)
arc4_bool_wtype: typing.Final = ARC4Type(
name="arc4.bool", stub_name=constants.CLS_ARC4_BOOL, alias="bool"
)
# TODO: move these validation functions somewhere else
def valid_base32(s: str) -> bool:
"""check if s is a valid base32 encoding string and fits into AVM bytes type"""
try:
value = base64.b32decode(s)
except ValueError:
return False
return bytes_wtype.is_valid_literal(value)
# regex from PyTEAL, appears to be RFC-4648
# ^(?:[A-Z2-7]{8})*(?:([A-Z2-7]{2}([=]{6})?)|([A-Z2-7]{4}([=]{4})?)|([A-Z2-7]{5}([=]{3})?)|([A-Z2-7]{7}([=]{1})?))? # noqa: E501
def valid_base16(s: str) -> bool:
try:
value = base64.b16decode(s)
except ValueError:
return False
return bytes_wtype.is_valid_literal(value)
def valid_base64(s: str) -> bool:
"""check if s is a valid base64 encoding string and fits into AVM bytes type"""
try:
value = base64.b64decode(s, validate=True)
except ValueError:
return False
return bytes_wtype.is_valid_literal(value)
# regex from PyTEAL, appears to be RFC-4648
# ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
def valid_address(address: str) -> bool:
"""check if address is a valid address with checksum"""
# Pad address so it's a valid b32 string
padded_address = address + (6 * "=")
if not (len(address) == ENCODED_ADDRESS_LENGTH and valid_base32(padded_address)):
return False
address_bytes = base64.b32decode(padded_address)
if len(address_bytes) != PUBLIC_KEY_HASH_LENGTH + ADDRESS_CHECKSUM_LENGTH:
return False
public_key_hash = address_bytes[:PUBLIC_KEY_HASH_LENGTH]
check_sum = address_bytes[PUBLIC_KEY_HASH_LENGTH:]
verified_check_sum = sha512_256_hash(public_key_hash)[-ADDRESS_CHECKSUM_LENGTH:]
return check_sum == verified_check_sum
def is_transaction_type(wtype: WType) -> typing.TypeGuard[WGroupTransaction]:
return isinstance(wtype, WGroupTransaction)
def is_inner_transaction_type(wtype: WType) -> typing.TypeGuard[WInnerTransaction]:
return isinstance(wtype, WInnerTransaction)
def is_inner_transaction_tuple_type(wtype: WType) -> typing.TypeGuard[WTuple]:
return isinstance(wtype, WTuple) and all(is_inner_transaction_type(t) for t in wtype.types)
def is_inner_transaction_params_type(wtype: WType) -> typing.TypeGuard[WInnerTransactionFields]:
return isinstance(wtype, WInnerTransactionFields)
def is_reference_type(wtype: WType) -> bool:
return wtype in (asset_wtype, account_wtype, application_wtype)
def is_arc4_encoded_type(wtype: WType) -> typing.TypeGuard[ARC4Type]:
return isinstance(wtype, ARC4Type)
def is_arc4_argument_type(wtype: WType) -> bool:
return (
is_arc4_encoded_type(wtype)
or is_reference_type(wtype)
or (is_transaction_type(wtype) and wtype.transaction_type is not None)
)
def has_arc4_equivalent_type(wtype: WType) -> bool:
"""
Checks if a non-arc4 encoded type has an arc4 equivalent
"""
if wtype in (bool_wtype, uint64_wtype, bytes_wtype, biguint_wtype):
return True
match wtype:
case WTuple(types=types):
return all(has_arc4_equivalent_type(t) and not isinstance(t, WTuple) for t in types)
return False
def avm_to_arc4_equivalent_type(wtype: WType) -> WType:
if wtype is bool_wtype:
return arc4_bool_wtype
if wtype is uint64_wtype:
return ARC4UIntN.from_scale(64)
if wtype is biguint_wtype:
return ARC4UIntN.from_scale(512)
if wtype is bytes_wtype:
return ARC4DynamicArray.from_element_type(
element_type=ARC4UIntN.from_scale(8, alias="byte")
)
if isinstance(wtype, WTuple):
return ARC4Tuple.from_types(types=[avm_to_arc4_equivalent_type(t) for t in wtype.types])
raise InternalError(f"{wtype} does not have an arc4 equivalent type")
def arc4_to_avm_equivalent_wtype(arc4_wtype: WType) -> WType:
match arc4_wtype:
case ARC4UIntN(n=n) | ARC4UFixedNxM(n=n):
return uint64_wtype if n <= 64 else biguint_wtype
case ARC4Tuple(types=types):
return WTuple.from_types(types)
case ARC4DynamicArray(element_type=ARC4UIntN(n=8)):
return bytes_wtype
if arc4_wtype is arc4_string_wtype:
return bytes_wtype
elif arc4_wtype is arc4_bool_wtype:
return bool_wtype
raise InternalError(f"Invalid arc4_wtype: {arc4_wtype}")