o
    >hS                     @   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*   t/var/www/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/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`.
        )r'   r)   r*   r*   r+   r   H      zEthereumKey.security_modulec                 C   r-   )zJ
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_no`.
        )r(   r.   r*   r*   r+   r   O   r/   zEthereumKey.key_noc                 C      dS )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_type`.
        ethereumr*   r.   r*   r*   r+   key_typeV      zEthereumKey.key_typeFbinaryc                 C      t  )zN
        Implements :meth:`autobahn.wamp.interfaces.IKey.public_key`.
        NotImplementedErrorr)   r4   r*   r*   r+   
public_key]   s   zEthereumKey.public_keyc                 C   r-   )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.can_sign`.
        )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`.
        r6   )r)   r=   r*   r*   r+   signs   r/   zEthereumKey.sign	signaturec                 C   r5   )zK
        Implements :meth:`autobahn.wamp.interfaces.IKey.recover`.
        r6   )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   iN)r'   rB   rC   r   r   r   r   r   rE   rF   rG   rH   r#   )	r)   r=   r?   rK   rL   r9   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   )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)TrQ   )r    r%   
ValueErrorformatlenr
   from_keyr   )rR   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/{})str_derivation_pathrT   TrQ   )rV   r   r    r%   rW   r
   rX   r   )rR   r[   r\   derivation_pathrD   rY   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RuntimeErrorrV   r   getr   rS   rZ   r;   r<   )rR   r`   r=   privkey_eth_hex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   rP   classmethodrS   rZ   r_   rk   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)   rt   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 open)rv   rW   rx   r.   r*   r*   r+   __len__  s   
zSecurityModuleMemory.__len__r   c                 C   s   | j sJ d|| jv S Nr|   rv   rx   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__`
        r|   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__`
        r|   zkey_no {} not found)rv   rx   
IndexErrorrV   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 )Nr|   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 r~   )rv   rx   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)rv   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`
        r|   FTNrv   rw   rF   rH   r.   r*   r*   r+   closeX  s   
zSecurityModuleMemory.closec                 C   r-   )z<
        Implements :meth:`ISecurityModule.is_open`
        )rv   r.   r*   r*   r+   rB   b  r/   zSecurityModuleMemory.is_openc                 C   r0   )z=
        Implements :meth:`ISecurityModule.can_lock`
        Tr*   r.   r*   r*   r+   can_locki  r3   zSecurityModuleMemory.can_lockc                 C   r-   )z>
        Implements :meth:`ISecurityModule.is_locked`
        )rw   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`
        r|   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`
        r|   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 )	Nr|   
cryptosignrT   T)rD   r   r   r   r1   )r   r   r   r   zinvalid key_type "{}")rv   rW   rx   r   naclsigning
SigningKeyrc   urandomr   r
   rX   rU   rV   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 r~   )rv   rx   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`
        r|   )rv   rc   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`
        r|   r   )rv   ru   acquirery   rh   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`
        r|   r      )rv   ru   r   ry   r   rF   rH   r   r*   r*   r+   increment_counter  s   





z&SecurityModuleMemory.increment_counterr   r[   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.
        rt   )ranger   r_   appendr   r   )rR   r[   r   r   rt   r{   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 "{}"rb   Nprivate-key-ed25519r   )configparserConfigParserreadhas_sectionrg   rV   
has_optionrc   rd   joindirnamerh   re   rf   r   r   r   rZ   r;   r<   r   r   )
rR   r   r   rt   cfgr   r=   ri   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.
        ra   rb   Nz)"private-key-eth" not found in keyfile {}r   z-"private-key-ed25519" not found in keyfile {}r   )rc   rd   re   rf   rg   rV   r   rh   r   r   rZ   r;   r<   r   r   )rR   r`   rt   r=   ri   r   r   r*   r*   r+   rk     s   	
z!SecurityModuleMemory.from_keyfiler   )r   r   )r   )&rl   rm   rn   ro   r   r   r   r   r   r,   rq   r}   rp   r   r   r   r   r   r   r   r   rr   rB   r   rC   r   r   r$   r   r   r%   r   r   r   rs   r_   r   rk   r*   r*   r*   r+   r     sH     
		


		)r   ),r;   rc   r   collections.abcr   typingr   r   r   r   r   r   	threadingr	   rF   r   eth_account.accountr
   eth_account.signers.localr   py_eth_sig_utils.eip712r   py_eth_sig_utils.utilsr   r   r   r   py_eth_sig_utils.signingr   r   autobahn.wamp.interfacesr   r   autobahn.xbr._mnemonicr   autobahn.utilr   autobahn.wamp.cryptosignr   __all__objectr   registerr   r*   r*   r*   r+   <module>   s2     
Z  *