4
4
from ethereum import utils
5
5
from rlp .utils import decode_hex , encode_hex
6
6
from ethereum .utils import encode_int , zpad , big_endian_to_int , is_numeric , is_string , ceil32
7
- from ethereum .utils import isnumeric
7
+ from ethereum .utils import isnumeric , TT256 , TT255
8
8
import ast
9
9
10
10
@@ -145,35 +145,38 @@ class ValueOutOfBounds(EncodingError):
145
145
pass
146
146
147
147
148
- # Decode an integer
149
- def decint (n ):
148
+ # Decode an unsigned/signed integer
149
+ def decint (n , signed = False ):
150
150
if isinstance (n , str ):
151
151
n = utils .to_string (n )
152
- if is_numeric (n ) and n < 2 ** 256 and n >= - 2 ** 255 :
152
+
153
+ if is_numeric (n ):
154
+ min , max = (- TT255 ,TT255 - 1 ) if signed else (0 ,TT256 - 1 )
155
+ if n > max or n < min :
156
+ raise EncodingError ("Number out of range: %r" % n )
153
157
return n
154
- elif is_numeric (n ):
155
- raise EncodingError ( "Number out of range: %r" % n )
156
- elif is_string ( n ) and len ( n ) == 40 :
157
- return big_endian_to_int ( decode_hex ( n ))
158
- elif is_string ( n ) and len ( n ) <= 32 :
159
- return big_endian_to_int ( n )
160
- elif is_string ( n ) and len (n ) > 32 :
161
- raise EncodingError ( "String too long: %r" % n )
158
+ elif is_string (n ):
159
+ if len ( n ) == 40 :
160
+ n = decode_hex ( n )
161
+ if len ( n ) > 32 :
162
+ raise EncodingError ( "String too long: %r" % n )
163
+
164
+ i = big_endian_to_int (n )
165
+ return ( i - TT256 ) if signed and i >= TT255 else i
162
166
elif n is True :
163
167
return 1
164
168
elif n is False or n is None :
165
169
return 0
166
170
else :
167
171
raise EncodingError ("Cannot encode integer: %r" % n )
168
172
169
-
170
173
# Encodes a base datum
171
174
def encode_single (typ , arg ):
172
175
base , sub , _ = typ
173
176
# Unsigned integers: uint<sz>
174
177
if base == 'uint' :
175
178
sub = int (sub )
176
- i = decint (arg )
179
+ i = decint (arg , False )
177
180
178
181
if not 0 <= i < 2 ** sub :
179
182
raise ValueOutOfBounds (repr (arg ))
@@ -185,8 +188,8 @@ def encode_single(typ, arg):
185
188
# Signed integers: int<sz>
186
189
elif base == 'int' :
187
190
sub = int (sub )
188
- i = decint (arg )
189
- if not - 2 ** (sub - 1 ) <= i < 2 ** sub :
191
+ i = decint (arg , True )
192
+ if not - 2 ** (sub - 1 ) <= i < 2 ** ( sub - 1 ) :
190
193
raise ValueOutOfBounds (repr (arg ))
191
194
return zpad (encode_int (i % 2 ** sub ), 32 )
192
195
# Unsigned reals: ureal<high>x<low>
0 commit comments