o
    èó·i´S  ã                   @   s  d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZ d dlmZ d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZmZmZmZ d d	lmZmZ d d
lmZm Z  d dl!m"Z" d dl#m$Z$ d dl%m&Z& dZ'G dd„ de(ƒZ)e  *e)¡ G dd„ deƒZ+e *e+¡ dS )é    N)ÚMutableMapping)ÚOptionalÚUnionÚDictÚAnyÚListÚIterator)ÚLock)ÚAccount)ÚLocalAccount)Úencode_typed_data)ÚecsignÚecrecover_to_pubÚchecksum_encodeÚsha3)Úv_r_s_to_signatureÚsignature_to_v_r_s)ÚISecurityModuleÚIEthereumKey)Úmnemonic_to_private_key)Úparse_keyfile)ÚCryptosignKey)ÚEthereumKeyÚSecurityModuleMemoryc                   @   s–  e Zd ZdZ		d2deeeef dede	e
 de	e ddf
dd	„Zede	d
 fdd„ƒZede	e fdd„ƒZedefdd„ƒZd3dedeeef fdd„Zedefdd„ƒZd3dedeeef fdd„Zdedefdd„Zdededefdd„Zd4deeef defd d!„Zdeeef dedefd"d#„Zed$eeef dd fd%d&„ƒZed'edd fd(d)„ƒZed5d+ed,edd fd-d.„ƒZed/edd fd0d1„ƒZdS )6r   zQ
    Base class to implement :class:`autobahn.wamp.interfaces.IEthereumKey`.
    NÚkey_or_addressÚcan_signÚsecurity_moduleÚkey_noÚreturnc                 C   sZ   |rt |ƒtks
J ‚|| _|j| _nt |ƒttfv sJ ‚d | _|| _|| _|| _|| _	d S ©N)
Útyper   Ú_keyÚaddressÚ_addressÚstrÚbytesÚ	_can_signÚ_security_moduleÚ_key_no)Úselfr   r   r   r   © r*   úZC:\Users\psant\Downloads\PAF backend\school\venv\Lib\site-packages\autobahn/xbr/_secmod.pyÚ__init__8   s   

zEthereumKey.__init__r   c                 C   ó   | j S )zS
        Implements :meth:`autobahn.wamp.interfaces.IKey.security_module`.
        N)r'   ©r)   r*   r*   r+   r   H   ó   zEthereumKey.security_modulec                 C   r-   )zJ
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_no`.
        N)r(   r.   r*   r*   r+   r   O   r/   zEthereumKey.key_noc                 C   ó   dS )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_type`.
        ÚethereumNr*   r.   r*   r*   r+   Úkey_typeV   ó   zEthereumKey.key_typeFÚbinaryc                 C   ó   t ƒ ‚)zN
        Implements :meth:`autobahn.wamp.interfaces.IKey.public_key`.
        N©ÚNotImplementedError©r)   r4   r*   r*   r+   Ú
public_key]   s   zEthereumKey.public_keyc                 C   r-   )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.can_sign`.
        N)r&   r.   r*   r*   r+   r   c   r/   zEthereumKey.can_signc                 C   s   |rt  | jdd… ¡S | jS )zS
        Implements :meth:`autobahn.wamp.interfaces.IEthereumKey.address`.
        é   N)ÚbinasciiÚa2b_hexr#   r8   r*   r*   r+   r"   j   s   zEthereumKey.addressÚdatac                 C   r5   )zH
        Implements :meth:`autobahn.wamp.interfaces.IKey.sign`.
        Nr6   )r)   r=   r*   r*   r+   Úsigns   r/   zEthereumKey.signÚ	signaturec                 C   r5   )zK
        Implements :meth:`autobahn.wamp.interfaces.IKey.recover`.
        Nr6   )r)   r=   r?   r*   r*   r+   Úrecoverz   r/   zEthereumKey.recoverTc              
   C   s’   | j r| j jr| j jrJ dƒ‚zt|ƒ}t|| jjƒ}t|Ž }W n ty7 } zt	 
|¡W  Y d}~S d}~ww |r?t	 |¡S t	 t |¡ ¡ ¡S )z[
        Implements :meth:`autobahn.wamp.interfaces.IEthereumKey.sign_typed_data`.
        ú)security module must be open and unlockedN)r'   Úis_openÚ	is_lockedr   r   r!   Úkeyr   Ú	ExceptionÚtxaioÚcreate_future_errorÚcreate_future_successr;   Úb2a_hexÚdecode)r)   r=   r4   Úmsg_hashÚsignature_vrsr?   Úer*   r*   r+   Úsign_typed_data�   s   €ÿ
zEthereumKey.sign_typed_datac           	   
   C   sš   | j r| j jr| j jrJ dƒ‚zt|ƒ}t|ƒ}t|g|¢R Ž }t|ƒdd… }t|ƒ}W n tyD } zt	 
|¡W  Y d}~S d}~ww t	 || jk¡S )z]
        Implements :meth:`autobahn.wamp.interfaces.IEthereumKey.verify_typed_data`.
        rA   iìÿÿÿN)r'   rB   rC   r   r   r   r   r   rE   rF   rG   rH   r#   )	r)   r=   r?   rK   rL   r9   Zaddress_bytesr"   rM   r*   r*   r+   Úverify_typed_dataœ   s   €ÿzEthereumKey.verify_typed_datar"   c                 C   s   t |dd�S )zÏ
        Create a public key from an address, which can be used to verify signatures.

        :param address: The Ethereum address (20 octets).
        :return: New instance of :class:`EthereumKey`
        F©r   r   N)r   )Úclsr"   r*   r*   r+   Úfrom_address­   s   zEthereumKey.from_addressrD   c                 C   sR   t |ƒtkrtd t |ƒ¡ƒ‚t|ƒdkrtd t|ƒ¡ƒ‚t |¡}t|dd�S )zÞ
        Create a private key from seed bytes, which can be used to sign and create signatures.

        :param key: The Ethereum private key seed (32 octets).
        :return: New instance of :class:`EthereumKey`
        z&invalid seed type {} (expected binary)é    z$invalid seed length {} (expected 32)TrP   N)r    r%   Ú
ValueErrorÚformatÚlenr
   Úfrom_keyr   )rQ   rD   Úaccountr*   r*   r+   Ú
from_bytes·   s   
zEthereumKey.from_bytesr   Ú
seedphraseÚindexc                 C   sL   d  |¡}t||d�}t|ƒtksJ ‚t|ƒdksJ ‚t |¡}t|dd�S )a„  
        Create a private key from the given BIP-39 mnemonic seed phrase and index,
        which can be used to sign and create signatures.

        :param seedphrase: The BIP-39 seedphrase ("Mnemonic") from which to derive the account.
        :param index: The account index in account hierarchy defined by the seedphrase.
        :return: New instance of :class:`EthereumKey`
        zm/44'/60'/0'/0/{})Zstr_derivation_pathrS   TrP   N)rU   r   r    r%   rV   r
   rW   r   )rQ   rZ   r[   Zderivation_pathrD   rX   r*   r*   r+   Úfrom_seedphraseÈ   s   

zEthereumKey.from_seedphraseÚkeyfilec                 C   s~   t j |¡rt j |¡std |¡ƒ‚t|ƒ}| dd¡}|du r7| dd¡}|du r2td |¡ƒ‚t 	|¡S t 
t |¡¡S )a  
        Create a public or private key from reading the given public or private key file.

        Here is an example key file that includes an Ethereum private key ``private-key-eth``, which
        is loaded in this function, and other fields, which are ignored by this function:

        .. code-block::

            This is a comment (all lines until the first empty line are comments indeed).

            creator: oberstet@intel-nuci7
            created-at: 2022-07-05T12:29:48.832Z
            user-id: oberstet@intel-nuci7
            public-key-ed25519: 7326d9dc0307681cc6940fde0e60eb31a6e4d642a81e55c434462ce31f95deed
            public-adr-eth: 0x10848feBdf7f200Ba989CDf7E3eEB3EC03ae7768
            private-key-ed25519: f750f42b0430e28a2e272c3cedcae4dcc4a1cf33bc345c35099d3322626ab666
            private-key-eth: 4d787714dcb0ae52e1c5d2144648c255d660b9a55eac9deeb80d9f506f501025

        :param keyfile: Path (relative or absolute) to a public or private keys file.
        :return: New instance of :class:`EthereumKey`
        úkeyfile "{}" is not a fileúprivate-key-ethNzpublic-adr-ethzBneither "private-key-eth" nor "public-adr-eth" found in keyfile {})ÚosÚpathÚexistsÚisfileÚRuntimeErrorrU   r   Úgetr   rR   rY   r;   r<   )rQ   r]   r=   Úprivkey_eth_hexZpub_adr_ethr*   r*   r+   Úfrom_keyfileÜ   s   
zEthereumKey.from_keyfile)NN)F)T)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r$   r%   Úboolr   r   Úintr,   Úpropertyr   r   r2   r9   r   r"   r>   r@   r   r   rN   rO   ÚclassmethodrR   rY   r\   rg   r*   r*   r*   r+   r   3   sB    þÿþ
þ		r   c                
   @   s®  e Zd ZdZd>deeeeef   fdd„Z	de
fdd„Zd	e
defd
d„Zdee
 fdd„Zd	e
deeef fdd„Zd	e
deeef ddfdd„Zd	e
ddfdd„Zdd„ Zdd„ Zedefdd„ƒZedefdd„ƒZedefdd„ƒZdd „ Zd!d"„ Zd#ede
fd$d%„Zd	e
fd&d'„Zd(e
defd)d*„Zd+e
de
fd,d-„Z d+e
de
fd.d/„Z!e"	0	0d?d1ed2e
d3e
dd fd4d5„ƒZ#e"d@d7ed8edd fd9d:„ƒZ$e"d;edd fd<d=„ƒZ%dS )Ar   zO
    A transient, memory-based implementation of :class:`ISecurityModule`.
    NÚkeysc                 C   sH   t ƒ | _d| _d| _i | _i | _|r t|ƒD ]\}}|| j|< qd S d S )NFT)r	   Ú_mutexÚ_is_openÚ
_is_lockedÚ_keysÚ	_countersÚ	enumerate)r)   rp   ÚirD   r*   r*   r+   r,     s   þzSecurityModuleMemory.__init__r   c                 C   s   | j sJ dƒ‚t| jƒS )z<
        Implements :meth:`ISecurityModule.__len__`
        úsecurity module not openN)rr   rV   rt   r.   r*   r*   r+   Ú__len__  s   
zSecurityModuleMemory.__len__r   c                 C   s   | j sJ dƒ‚|| jv S ©Nrx   ©rr   rt   ©r)   r   r*   r*   r+   Ú__contains__&  s   
z!SecurityModuleMemory.__contains__c                 c   s    � | j sJ dƒ‚| jE dH  dS )z=
        Implements :meth:`ISecurityModule.__iter__`
        rx   Nr{   r.   r*   r*   r+   Ú__iter__+  s   €zSecurityModuleMemory.__iter__c                 C   s0   | j sJ dƒ‚|| jv r| j| S td |¡ƒ‚)z@
        Implements :meth:`ISecurityModule.__getitem__`
        rx   zkey_no {} not foundN)rr   rt   Ú
IndexErrorrU   r|   r*   r*   r+   Ú__getitem__3  s   

z SecurityModuleMemory.__getitem__rD   c                 C   s4   | j sJ dƒ‚|dksJ ‚|| jv r	 || j|< d S )Nrx   r   r{   )r)   r   rD   r*   r*   r+   Ú__setitem__>  s
   
z SecurityModuleMemory.__setitem__c                 C   s*   | j sJ dƒ‚|| jv r| j|= d S tƒ ‚rz   )rr   rt   r   r|   r*   r*   r+   Ú__delitem__G  s   
z SecurityModuleMemory.__delitem__c                 C   s   | j rJ dƒ‚d| _ t d¡S )z9
        Implements :meth:`ISecurityModule.open`
        zsecurity module already openTN)rr   rF   rH   r.   r*   r*   r+   ÚopenO  s   
zSecurityModuleMemory.openc                 C   s$   | j sJ dƒ‚d| _ d| _t d¡S )z:
        Implements :meth:`ISecurityModule.close`
        rx   FTN©rr   rs   rF   rH   r.   r*   r*   r+   ÚcloseX  s   
zSecurityModuleMemory.closec                 C   r-   )z<
        Implements :meth:`ISecurityModule.is_open`
        N)rr   r.   r*   r*   r+   rB   b  r/   zSecurityModuleMemory.is_openc                 C   r0   )z=
        Implements :meth:`ISecurityModule.can_lock`
        TNr*   r.   r*   r*   r+   Úcan_locki  r3   zSecurityModuleMemory.can_lockc                 C   r-   )z>
        Implements :meth:`ISecurityModule.is_locked`
        N)rs   r.   r*   r*   r+   rC   p  r/   zSecurityModuleMemory.is_lockedc                 C   s(   | j sJ dƒ‚| jrJ ‚d| _t d¡S )z9
        Implements :meth:`ISecurityModule.lock`
        rx   TNr„   r.   r*   r*   r+   Úlockw  ó   

zSecurityModuleMemory.lockc                 C   s(   | j sJ dƒ‚| jsJ ‚d| _t d¡S )z;
        Implements :meth:`ISecurityModule.unlock`
        rx   FNr„   r.   r*   r*   r+   Úunlock�  rˆ   zSecurityModuleMemory.unlockr2   c                 C   sˆ   | j sJ dƒ‚t| jƒ}|dkr ttj t d¡¡d| |d�}n|dkr3t	t
 t d¡¡d| |d�}ntd |¡ƒ‚|| j|< t |¡S )	Nrx   Z
cryptosignrS   T)rD   r   r   r   r1   )r   r   r   r   zinvalid key_type "{}")rr   rV   rt   r   ÚnaclZsigningZ
SigningKeyr`   Úurandomr   r
   rW   rT   rU   rF   rH   )r)   r2   r   rD   r*   r*   r+   Ú
create_key‹  s"   
ýý

zSecurityModuleMemory.create_keyc                 C   s4   | j sJ dƒ‚|| jv r| j|= t |¡S t d ¡S rz   )rr   rt   rF   rH   r|   r*   r*   r+   Ú
delete_keyž  s
   


zSecurityModuleMemory.delete_keyÚoctetsc                 C   s"   | j sJ dƒ‚t |¡}t |¡S )z?
        Implements :meth:`ISecurityModule.get_random`
        rx   N)rr   r`   r‹   rF   rH   )r)   rŽ   r=   r*   r*   r+   Ú
get_random§  s   

zSecurityModuleMemory.get_randomÚ
counter_noc                 C   s:   | j sJ dƒ‚| j ¡  | j |d¡}| j ¡  t |¡S )z@
        Implements :meth:`ISecurityModule.get_counter`
        rx   r   N)rr   rq   Úacquireru   re   ÚreleaserF   rH   ©r)   r�   Úresr*   r*   r+   Úget_counter°  s
   


z SecurityModuleMemory.get_counterc                 C   s\   | j sJ dƒ‚| j ¡  || jvrd| j|< | j|  d7  < | j| }| j ¡  t |¡S )zF
        Implements :meth:`ISecurityModule.increment_counter`
        rx   r   é   N)rr   rq   r‘   ru   r’   rF   rH   r“   r*   r*   r+   Úincrement_counter»  s   





z&SecurityModuleMemory.increment_counterr–   rZ   Únum_eth_keysÚnum_cs_keysc                 C   s^   g }t |ƒD ]}t ||¡}| |¡ qt |ƒD ]}t ||| ¡}| |¡ qt|d�}|S )aó  
        Create a new memory-backed security module with

        1. ``num_eth_keys`` keys of type :class:`EthereumKey`, followed by
        2. ``num_cs_keys`` keys of type :class:`CryptosignKey`

        computed from a (common) BIP44 seedphrase.

        :param seedphrase: BIP44 seedphrase to use.
        :param num_eth_keys: Number of Ethereum keys to derive.
        :param num_cs_keys: Number of Cryptosign keys to derive.
        :return: New memory-backed security module instance.
        ©rp   N)Úranger   r\   Úappendr   r   )rQ   rZ   r˜   r™   rp   rw   rD   Úsmr*   r*   r+   r\   É  s   
z$SecurityModuleMemory.from_seedphraseÚdefaultÚconfigÚprofilec           
      C   sî   g }t  ¡ }| |¡ | |¡std ||¡ƒ‚| |d¡s&td ||¡ƒ‚tj 	tj 
|¡| |d¡¡}tj |¡rAtj |¡sJtd |||¡ƒ‚t|ƒ}| dd¡}| t t |¡¡¡ | dd¡}| t t |¡¡¡ t|d�}	|	S )	ak  
        Create a new memory-backed security module with keys referred from a profile in
        the given configuration file.

        :param config: Path (relative or absolute) to an INI configuration file.
        :param profile: Name of the profile within the given INI configuration file.
        :return: New memory-backed security module instance.
        z1profile "{}" not found in configuration file "{}"ÚprivkeyzCmissing option "privkey" in profile "{}" of configuration file "{}"zEprivkey "{}" is not a file in profile "{}" of configuration file "{}"r_   Núprivate-key-ed25519rš   )ÚconfigparserÚConfigParserÚreadÚhas_sectionrd   rU   Ú
has_optionr`   ra   ÚjoinÚdirnamere   rb   rc   r   rœ   r   rY   r;   r<   r   r   )
rQ   rŸ   r    rp   Úcfgr¡   r=   rf   Úprivkey_ed25519_hexr�   r*   r*   r+   Úfrom_configé  s"   



z SecurityModuleMemory.from_configr]   c                 C   s°   g }t j |¡rt j |¡std |¡ƒ‚t|ƒ}| dd¡}|du r*td |¡ƒ‚| t	 
t |¡¡¡ | dd¡}|du rFtd |¡ƒ‚| t 
t |¡¡¡ t|d�}|S )a  
        Create a new memory-backed security module with keys referred from a profile in
        the given configuration file.

        :param keyfile: Path (relative or absolute) to a private keys file.
        :return: New memory-backed security module instance.
        r^   r_   Nz)"private-key-eth" not found in keyfile {}r¢   z-"private-key-ed25519" not found in keyfile {}rš   )r`   ra   rb   rc   rd   rU   r   re   rœ   r   rY   r;   r<   r   r   )rQ   r]   rp   r=   rf   r«   r�   r*   r*   r+   rg     s   	
z!SecurityModuleMemory.from_keyfiler   )r–   r–   )rž   )&rh   ri   rj   rk   r   r   r   r   r   r,   rm   ry   rl   r}   r   r~   r€   r�   r‚   rƒ   r…   rn   rB   r†   rC   r‡   r‰   r$   rŒ   r�   r%   r�   r•   r—   ro   r\   r¬   rg   r*   r*   r*   r+   r     sH     
		


		ÿÿÿ)r   ),r;   r`   r£   Úcollections.abcr   Útypingr   r   r   r   r   r   Ú	threadingr	   rF   rŠ   Zeth_account.accountr
   Zeth_account.signers.localr   Zpy_eth_sig_utils.eip712r   Zpy_eth_sig_utils.utilsr   r   r   r   Zpy_eth_sig_utils.signingr   r   Zautobahn.wamp.interfacesr   r   Zautobahn.xbr._mnemonicr   Zautobahn.utilr   Zautobahn.wamp.cryptosignr   Ú__all__Úobjectr   Úregisterr   r*   r*   r*   r+   Ú<module>   s2     
Z  *