
    (i/$              
           d Z ddlmZmZmZ ddlmZmZ ddlm	Z	m
Z
mZ ddhZdd	hZ G d
 de      Z G d de      Z G d de      Zdedededeeef   fdZ G d d      Zy)a  
Generate Heirarchical Deterministic Wallets (HDWallet).

Partially implements the BIP-0032, BIP-0043, and BIP-0044 specifications:

* BIP-0032: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
* BIP-0043: https://github.com/bitcoin/bips/blob/master/bip-0043.mediawiki
* BIP-0044: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki

Skips serialization and public key derivation as unnecssary for this library's purposes.

Notes
-----

* Integers are modulo the order of the curve (referred to as n).
* Addition (+) of two coordinate pair is defined as application of
  the EC group operation.
* Concatenation (||) is the operation of appending one byte sequence onto another.


Definitions
-----------

* point(p): returns the coordinate pair resulting from EC point multiplication
  (repeated application of the EC group operation) of the secp256k1 base point
  with the integer p.
* ser_32(i): serialize a 32-bit unsigned integer i as a 4-byte sequence,
  most significant byte first.
* ser_256(p): serializes the integer p as a 32-byte sequence, most significant
  byte first.
* ser_P(P): serializes the coordinate pair P = (x,y) as a byte sequence using SEC1's
  compressed form: (0x02 or 0x03) || ser_256(x), where the header byte depends on the
  parity of the omitted y coordinate.
* parse_256(p): interprets a 32-byte sequence as a 256-bit number, most significant
  byte first.

    )TupleTypeUnion)ValidationErrorto_int   )SECP256K1_Nec_pointhmac_sha512mM'Hc                       e Zd ZU dZdZdZeed<   dedd fdZde	fdZ
dedd fd	Zdefd
Zde	fdZede	ded   fd       Zy)Nodez
    A base node class.
     r   indexreturnc                     d|kD  s|dkD  rt        |  d|       t        j                  | || j                  z         }||_        |S )Nr           z" cannot be initialized with value )r   int__new__OFFSETr   )clsr   objs      T/var/www/br/venv/lib/python3.12/site-packages/eth_account/hdaccount/deterministic.pyr   zNode.__new__N   sK    u9!SE)KE7"STTkk#uszz12	
    c                 N    | j                   j                   d| j                   dS )N())	__class____name__r   selfs    r   __repr__zNode.__repr__V   s$    ..))*!DJJ<q99r   otherc                 >    | j                  | j                  |z         S N)r!   r   )r$   r&   s     r   __add__zNode.__add__Y   s    ~~djj5011r   c                 (    | j                  dd      S )N   big	byteorder)to_bytesr#   s    r   	serializezNode.serialize\   s    }}Q%}00r   c                 F    t        | j                        | j                  z   S r(   )strr   TAGr#   s    r   encodezNode.encode_   s    4::))r   node)SoftNodeHardNodec                     t        |       dk  rt        d      | d   t        v rt        }| d d }nt        }| }	 t        |      } ||      S # t        $ r}t        d| d      |d }~ww xY w)Nr   zCannot use empty stringr   z' is not a valid node index.)lenr   HARD_NODE_SUFFIXESr7   r6   r   
ValueError)r5   
node_class
node_index
node_valueerrs        r   decodezNode.decodeb   s    t9q=!";<< 8))!JcrJ!JJ	YZJ *%%  	Y!Aj\1M"NOUXX	Ys   A 	A+A&&A+N)r"   
__module____qualname____doc__r3   r   r   __annotations__r   r2   r%   r)   bytesr0   r4   staticmethodr   rA    r   r   r   r   E   s     CFJC F :# :2S 2V 215 1* * &S &U#9: & &r   r   c                       e Zd ZdZdZdZy)r6   z7
    Soft node (unhardened), where value = index .
    r   r   Nr"   rB   rC   rD   r3   r   rH   r   r   r6   r6   w   s     CFr   r6   c                       e Zd ZdZdZdZy)r7   zD
    Hard node, where value = index + BIP32_HARDENED_CONSTANT .
    r   r   NrJ   rH   r   r   r7   r7      s     CFr   r7   
parent_keyparent_chain_coder5   r   c                 n   t        |      dk(  sJ t        |t              r1t        |       dk(  sJ t        |d| z   |j	                         z         }n^t        |t
              r@t        t        |             dk(  sJ t        |t        |       |j	                         z         }nt        d|       t        |      dk(  sJ t        |dd       t        k\  rt        | ||dz         S t        |dd       t        |       z   t        z  }|dk(  rt        | ||dz         S |j                  dd	
      }|dd }||fS )u  
    Compute a derivative key from the parent key.

    From BIP32:

    The function CKDpriv((k_par, c_par), i) → (k_i, c_i) computes a child extended
    private key from the parent extended private key:

    1. Check whether the child is a hardened key (i ≥ 2**31).
       If the child is a hardened key,
       let I = HMAC-SHA512(Key = c_par, Data = 0x00 || ser_256(k_par) || ser_32(i)).
       (Note: The 0x00 pads the private key to make it 33 bytes long.)
       If it is not a hardened key, then
       let I = HMAC-SHA512(Key = c_par, Data = ser_P(point(k_par)) || ser_32(i)).
    2. Split I into two 32-byte sequences, I_L and I_R.
    3. The returned child key k_i is parse_256(I_L) + k_par (mod n).
    4. The returned chain code c_i is I_R.
    5. In case parse_256(I_L) ≥ n or k_i = 0, the resulting key is invalid,
       and one should proceed with the next value for i.
       (Note: this has probability lower than 1 in 2**127.)

            !   zCannot process: @   Nr   r   r,   r-   )r:   
isinstancer7   r   r0   r6   r
   r   r   r	   derive_child_keyr/   )rL   rM   r5   child	child_keychild_key_byteschild_chain_codes          r   rT   rT      sG   6  !R'''$!:"$$$-w/CdnnFV/VW	D(	#8J'(B...-x
/CdnnFV/VW  0788u:eCRj[(
,=taxHHcr
#fZ&88KGIA~
,=taxHH((u(=ORSz,,,r   c                   @    e Zd ZdefdZdefdZdefdZdedefdZy)	HDPathpathc           
      `   t        |      dk  rt        d      |j                  d      }|d   t        vrt        d| d      g }t	        |dd       D ]*  \  }}	 |j                  t        j                  |             , || _        y# t        $ r}t        d| d	| d
|       |d}~ww xY w)aY  
        Create a new Hierarchical Deterministic path by decoding the given path.

        Initializes an hd account generator using the
        given path string (from BIP-0032). The path is decoded into nodes of the
        derivation key tree, which define a pathway from a given main seed to
        the child key that is used for a given purpose. Please also reference BIP-
        0043 (which definites the first level as the "purpose" field of an HD path)
        and BIP-0044 (which defines a commonly-used, 5-level scheme for BIP32 paths)
        for examples of how this object may be used. Please note however that this
        object makes no such assumptions of the use of BIP43 or BIP44, or later BIPs.
        :param path             : BIP32-compatible derivation path
        :type path              : str as "m/idx_0/.../idx_n" or "m/idx_0/.../idx_n"
                                  where idx_* is either an integer value (soft node)
                                  or an integer value followed by either the "'" char
                                  or the "H" char (hardened node)
        r   z$Cannot parse path from empty string./r   zPath is not valid: "z". Must start with "m"NzPath "z!" is not valid. Issue with node "z": )	r:   r   splitBASE_NODE_IDENTIFIERS	enumerateappendr   rA   _path)r$   r[   nodesdecoded_path_idxr5   r@   s          r   __init__zHDPath.__init__   s    $ t9q=!"HII

3800!$8>T"UVV#E!"I. 	JD$##DKK$56	 "
 # %TF"CD6SERs   $B

	B-B((B-r   c                 V    | j                   j                   d| j                          dS )Nz(path="z"))r!   r"   r4   r#   s    r   r%   zHDPath.__repr__   s&    ..))*'$++-CCr   c                 b    dt        d | j                  D              z   }dj                  |      S )z]
        Encodes this class to a string (reversing the decoding in the constructor).
        )r   c              3   <   K   | ]  }|j                           y wr(   )r4   ).0r5   s     r   	<genexpr>z HDPath.encode.<locals>.<genexpr>   s     %Kdkkm%Ks   r]   )tuplerb   join)r$   encoded_paths     r   r4   zHDPath.encode   s,     %K

%K KKxx%%r   seedc                 t    t        d|      }|dd }|dd }| j                  D ]  }t        |||      \  }} |S )a3  
        Perform the BIP32 Hierarchical Derivation recursive loop with the given Path.

        Note that the key and chain_code are initialized with the main seed, and that
        the key that is returned is the child key at the end of derivation process (and
        the chain code is discarded)
        s   Bitcoin seedNrO   )r   rb   rT   )r$   ro   	main_nodekey
chain_coder5   s         r   derivezHDPath.derive   sR      6	nrs^
JJ 	FD.sJEOC	F
r   N)	r"   rB   rC   r2   rf   r%   r4   rF   rt   rH   r   r   rZ   rZ      s<    ""S ""HD# D& &5 U r   rZ   N)rD   typingr   r   r   	eth_utilsr   r   _utilsr	   r
   r   r_   r;   r   r   r6   r7   rF   rT   rZ   rH   r   r   <module>rx      s   $^ 
  c
 3Z /&3 /&dt t 5-5-5- 5- 5%<	5-p< <r   