33from enum import Enum
44
55from pactus .crypto .hrp import HRP
6+ from pactus .encoding import encoding
67from pactus .utils import utils
78
89# Address format: hrp + `1` + type + data + checksum
@@ -22,7 +23,7 @@ class AddressType(Enum):
2223class Address :
2324 def __init__ (self , address_type : AddressType , data : bytes ) -> None :
2425 if len (data ) != ADDRESS_SIZE - 1 :
25- msg = "Data must be 21 bytes long"
26+ msg = "Data must be 20 bytes long"
2627 raise ValueError (msg )
2728
2829 self .data = bytearray ()
@@ -32,7 +33,7 @@ def __init__(self, address_type: AddressType, data: bytes) -> None:
3233 @classmethod
3334 def from_string (cls , text : str ) -> Address :
3435 if text == TREASURY_ADDRESS_STRING :
35- return bytes ([ 0 ] )
36+ return cls ( AddressType . TREASURY , bytes (20 ) )
3637
3738 hrp , typ , data = utils .decode_to_base256_with_type (text )
3839 if hrp != HRP .ADDRESS_HRP :
@@ -59,7 +60,7 @@ def raw_bytes(self) -> bytes:
5960 return bytes (self .data )
6061
6162 def string (self ) -> str :
62- if self .data == bytes ([ 0 ] ):
63+ if self .is_treasury_address ( ):
6364 return TREASURY_ADDRESS_STRING
6465
6566 return utils .encode_from_base256_with_type (
@@ -76,7 +77,30 @@ def is_treasury_address(self) -> bool:
7677
7778 def is_account_address (self ) -> bool :
7879 t = self .address_type ()
79- return t in (AddressType .TREASURY , AddressType .BLS_ACCOUNT , AddressType .ED25519_ACCOUNT )
80+ return t in (
81+ AddressType .TREASURY ,
82+ AddressType .BLS_ACCOUNT ,
83+ AddressType .ED25519_ACCOUNT ,
84+ )
8085
8186 def is_validator_address (self ) -> bool :
8287 return self .address_type () == AddressType .VALIDATOR
88+
89+ def encode (self ) -> bytes :
90+ buf = b""
91+ if self .is_treasury_address ():
92+ return encoding .append_uint8 (buf , AddressType .TREASURY .value )
93+ return encoding .append_fixed_bytes (buf , self .raw_bytes ())
94+
95+ @classmethod
96+ def decode (cls , buf : bytes ) -> tuple :
97+ """
98+ Decode an Address from bytes.
99+ Returns (Address, remaining_buf).
100+ """
101+ addr_type , buf = encoding .read_uint8 (buf )
102+ if addr_type == AddressType .TREASURY .value :
103+ return cls (AddressType .TREASURY , bytes (20 )), buf
104+
105+ data , buf = encoding .read_fixed_bytes (buf , 20 )
106+ return cls (AddressType (addr_type ), data ), buf
0 commit comments