
    tfS                     b   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e(          Z) e j*        e)            G d de          Z+ ej*        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                   *   e Zd ZdZ	 	 d#deeeef         dede	e
         de	e         ddf
dZede	d	         fd
            Zede	e         fd            Zedefd            Zd$dedeeef         fdZedefd            Zd$dedeeef         fdZdedefdZdededefdZd%deeef         defdZdeeef         dedefdZedeeef         dd fd            Zededd fd            Zed&dededd fd             Zed!edd fd"            ZdS )'r   zQ
    Base class to implement :class:`autobahn.wamp.interfaces.IEthereumKey`.
    Nkey_or_addresscan_signsecurity_modulekey_noreturnc                     |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   s        S/var/www/surfInsights/venv3-11/lib/python3.11/site-packages/autobahn/xbr/_secmod.py__init__zEthereumKey.__init__8   s}      	+''<7777&DI*2DMM''C<7777DI*DM! /    r   c                     | j         S )zS
        Implements :meth:`autobahn.wamp.interfaces.IKey.security_module`.
        )r*   r,   s    r-   r   zEthereumKey.security_moduleH   s    
 $$r/   c                     | j         S )zJ
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_no`.
        )r+   r1   s    r-   r   zEthereumKey.key_noO   s    
 |r/   c                     dS )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.key_type`.
        ethereum r1   s    r-   key_typezEthereumKey.key_typeV   s	    
 zr/   Fbinaryc                     t                      )zN
        Implements :meth:`autobahn.wamp.interfaces.IKey.public_key`.
        NotImplementedErrorr,   r7   s     r-   
public_keyzEthereumKey.public_key]   s     "###r/   c                     | j         S )zL
        Implements :meth:`autobahn.wamp.interfaces.IKey.can_sign`.
        )r)   r1   s    r-   r   zEthereumKey.can_signc   s    
 ~r/   c                 V    |r!t          j        | j        dd                   S | j        S )zS
        Implements :meth:`autobahn.wamp.interfaces.IEthereumKey.address`.
           N)binasciia2b_hexr&   r;   s     r-   r%   zEthereumKey.addressj   s0      	!#DM!""$5666= r/   datac                     t                      )zH
        Implements :meth:`autobahn.wamp.interfaces.IKey.sign`.
        r9   )r,   rB   s     r-   signzEthereumKey.signs       
 "###r/   	signaturec                     t                      )zK
        Implements :meth:`autobahn.wamp.interfaces.IKey.recover`.
        r9   )r,   rB   rF   s      r-   recoverzEthereumKey.recoverz   rE   r/   Tc                    | j         r"| j         j        r| j         j        r
J d            	 t          |          }t	          || j        j                  }t          | }|rt          j	        |          S t          j	        t          j        |                                                    S # t          $ r}t          j        |          cY d}~S d}~ww xY w)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   txaiocreate_future_successr@   b2a_hexdecode	Exceptioncreate_future_error)r,   rB   r7   msg_hashsignature_vrsrF   es          r-   sign_typed_datazEthereumKey.sign_typed_data   s      	F(0  F9N9X  F  F  [F  F  F  F	Y(..H #8TY];;M +M:I  Y29===283CI3N3N3U3U3W3WXXX  	0 	0 	0,Q////////	0s   2B+ +
C5CCCc                    | j         r"| j         j        r| j         j        r
J d            	 t          |          }t	          |          }t          |g|R  }t          |          dd         }t          |          }t          j	        || j
        k              S # t          $ r}t          j        |          cY d}~S d}~ww xY w)z]
        Implements :meth:`autobahn.wamp.interfaces.IEthereumKey.verify_typed_data`.
        rJ   iN)r*   rK   rL   r   r   r   r   r   rN   rO   r&   rR   rS   )	r,   rB   rF   rT   rU   r<   address_bytesr%   rV   s	            r-   verify_typed_datazEthereumKey.verify_typed_data   s       	F(0  F9N9X  F  F  [F  F  F  F		I(..H.y99M)(C]CCCJ ,,STT2M%m44G .w$-/GHHH  	0 	0 	0,Q////////	0s   AB 
C#B<6C<Cr%   c                 $    t          |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%   s     r-   from_addresszEthereumKey.from_address   s     'EBBBBr/   rM   c                 ^   t          |          t          k    r/t          d                    t          |                              t	          |          dk    r/t          d                    t	          |                              t          j        |          }t          |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)Tr\   )r#   r(   
ValueErrorformatlenr   from_keyr   )r]   rM   accounts      r-   
from_byteszEthereumKey.from_bytes   s     99ELLTRUYYWWXXXs88r>>CJJ3s88TTUUU ' 0 5 5'DAAAAr/   r   
seedphraseindexc                     d                     |          }t          ||          }t          |          t          k    sJ t	          |          dk    sJ t          j        |          }t          |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_pathr`   Tr\   )rb   r   r#   r(   rc   r   rd   r   )r]   rg   rh   derivation_pathrM   re   s         r-   from_seedphrasezEthereumKey.from_seedphrase   sv     .44U;;%joVVVCyyE!!!!3xx2~~~~ ' 0 5 5'DAAAAr/   keyfilec                    t           j                            |          rt           j                            |          s"t	          d                    |                    t          |          }|                    dd          }|T|                    dd          }|"t	          d                    |                    t          	                    |          S t          
                    t          j        |                    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RuntimeErrorrb   r   getr   r^   rf   r@   rA   )r]   rm   rB   privkey_eth_hexpub_adr_eths        r-   from_keyfilezEthereumKey.from_keyfile   s    . w~~g&& 	MbgnnW.E.E 	M;BB7KKLLL W%%((#4d;;"((#3T::K""#g#n#nov#w#wxxx"//<<<))(*:?*K*KLLLr/   )NN)F)T)r   )__name__
__module____qualname____doc__r   r   r'   r(   boolr   r   intr.   propertyr   r   r6   r<   r   r%   rD   rH   r   r   rW   rZ   classmethodr^   rf   rl   ry   r5   r/   r-   r   r   3   s$        
 ?C)- u\3-E'F RV "*?";!#26     %*;!< % % % X%     X #    X$ $ $%U
2C $ $ $ $ $    X! !d !uS%Z/@ ! ! ! !$ $5 $ $ $ $$E $e $ $ $ $ $Y YDcN YE Y Y Y Y6Id38n I I4 I I I I" C5e#4 C C C C [C BU B} B B B [B  B B BS B B B B [B& ,M3 ,M= ,M ,M ,M [,M ,M ,Mr/   r   c            
          e Zd ZdZd(deeeeef                           fdZ	de
fdZde
defdZdee
         fd	Zde
deeef         fd
Zde
deeef         ddfdZde
ddfdZd Zd Zedefd            Zedefd            Zedefd            Zd Zd Zdede
fdZde
fdZde
defdZde
de
fdZ de
de
fdZ!e"	 	 d)dede
d e
dd fd!            Z#e"d*d#ed$edd fd%            Z$e"d&edd fd'            Z%dS )+r   zO
    A transient, memory-based implementation of :class:`ISecurityModule`.
    Nkeysc                     t                      | _        d| _        d| _        i | _        i | _        |rt          |          D ]\  }}|| j        |<   d S d S )NFT)r
   _mutex_is_open
_is_locked_keys	_counters	enumerate)r,   r   irM   s       r-   r.   zSecurityModuleMemory.__init__  sk    ffCE
)+ 	$#D// $ $3 #
1	$ 	$$ $r/   r    c                 L    | j         s
J d            t          | j                  S )z<
        Implements :meth:`ISecurityModule.__len__`
        security module not open)r   rc   r   r1   s    r-   __len__zSecurityModuleMemory.__len__  s)     }8888884:r/   r   c                 6    | j         s
J d            || j        v S Nr   r   r   r,   r   s     r-   __contains__z!SecurityModuleMemory.__contains__&  s&    }888888##r/   c              #   F   K   | j         s
J d            | j        E d{V  dS )z=
        Implements :meth:`ISecurityModule.__iter__`
        r   Nr   r1   s    r-   __iter__zSecurityModuleMemory.__iter__+  s?       }888888:r/   c                     | j         s
J d            || j        v r| j        |         S t          d                    |                    )z@
        Implements :meth:`ISecurityModule.__getitem__`
        r   zkey_no {} not found)r   r   
IndexErrorrb   r   s     r-   __getitem__z SecurityModuleMemory.__getitem__3  sR     }888888TZ:f%%299&AABBBr/   rM   c                 `    | j         s
J d            |dk    sJ || j        v r	 || j        |<   d S )Nr   r   r   )r,   r   rM   s      r-   __setitem__z SecurityModuleMemory.__setitem__>  sH    }888888{{{{TZ 
6r/   c                 f    | j         s
J d            || j        v r
| j        |= d S t                      r   )r   r   r   r   s     r-   __delitem__z SecurityModuleMemory.__delitem__G  s@    }888888TZ
6""",,r/   c                 Z    | j         r
J d            d| _         t          j        d          S )z9
        Implements :meth:`ISecurityModule.open`
        zsecurity module already openTN)r   rN   rO   r1   s    r-   openzSecurityModuleMemory.openO  s3     =@@"@@@@*4000r/   c                 h    | j         s
J d            d| _         d| _        t          j        d          S )z:
        Implements :meth:`ISecurityModule.close`
        r   FTNr   r   rN   rO   r1   s    r-   closezSecurityModuleMemory.closeX  s:     }888888*4000r/   c                     | j         S )z<
        Implements :meth:`ISecurityModule.is_open`
        )r   r1   s    r-   rK   zSecurityModuleMemory.is_openb  s    
 }r/   c                     dS )z=
        Implements :meth:`ISecurityModule.can_lock`
        Tr5   r1   s    r-   can_lockzSecurityModuleMemory.can_locki  s	    
 tr/   c                     | j         S )z>
        Implements :meth:`ISecurityModule.is_locked`
        )r   r1   s    r-   rL   zSecurityModuleMemory.is_lockedp  s    
 r/   c                 l    | j         s
J d            | j        rJ d| _        t          j        d          S )z9
        Implements :meth:`ISecurityModule.lock`
        r   TNr   r1   s    r-   lockzSecurityModuleMemory.lockw  sA     }888888?"""*4000r/   c                 l    | j         s
J d            | j        sJ d| _        t          j        d          S )z;
        Implements :meth:`ISecurityModule.unlock`
        r   FNr   r1   s    r-   unlockzSecurityModuleMemory.unlock  sA     }888888*4000r/   r6   c                    | j         s
J d            t          | j                  }|dk    rCt          t          j                            t          j        d                    d| |          }n`|dk    r8t          t          j        t          j        d                    d| |          }n"t          d                    |                    || j        |<   t          j        |          S )	Nr   
cryptosignr`   T)rM   r   r   r   r4   )r   r   r   r   zinvalid key_type "{}")r   rc   r   r   naclsigning
SigningKeyrq   urandomr   r   rd   ra   rb   rN   rO   )r,   r6   r   rM   s       r-   
create_keyzSecurityModuleMemory.create_key  s    }888888TZ|##DL$;$;BJrNN$K$K)-04'-/ / /CC ##W-=bjnn-M-M'+.2%+- - -CC
 4;;HEEFFF 
6*6222r/   c                     | j         s
J d            || j        v r| j        |= t          j        |          S t          j        d           S r   )r   r   rN   rO   r   s     r-   
delete_keyzSecurityModuleMemory.delete_key  sR    }888888TZ
6".v666.t444r/   octetsc                 t    | j         s
J d            t          j        |          }t          j        |          S )z?
        Implements :meth:`ISecurityModule.get_random`
        r   )r   rq   r   rN   rO   )r,   r   rB   s      r-   
get_randomzSecurityModuleMemory.get_random  s;     }888888z&!!*4000r/   
counter_noc                     | j         s
J d            | j                                         | j                            |d          }| j                                         t          j        |          S )z@
        Implements :meth:`ISecurityModule.get_counter`
        r   r   )r   r   acquirer   rv   releaserN   rO   r,   r   ress      r-   get_counterz SecurityModuleMemory.get_counter  sk     }888888n  Q//*3///r/   c                    | j         s
J d            | j                                         || j        vr
d| j        |<   | j        |xx         dz  cc<   | j        |         }| j                                         t          j        |          S )zF
        Implements :meth:`ISecurityModule.increment_counter`
        r   r      )r   r   r   r   r   rN   rO   r   s      r-   increment_counterz&SecurityModuleMemory.increment_counter  s     }888888T^++)*DN:&z"""a'"""nZ(*3///r/   r   rg   num_eth_keysnum_cs_keysc                 ,   g }t          |          D ]2}t                              ||          }|                    |           3t          |          D ]/}t	          j        |||z             }|                    |           0t          |          }|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.
        r   )ranger   rl   appendr   r   )r]   rg   r   r   r   r   rM   sms           r-   rl   z$SecurityModuleMemory.from_seedphrase  s      9; |$$ 	 	A--j!<<CKK {## 	 	A/
A<LMMCKK "t,,,	r/   defaultconfigprofilec                 (   g }t          j                    }|                    |           |                    |          s#t	          d                    ||                    |                    |d          s#t	          d                    ||                    t          j        	                    t          j        
                    |          |                    |d                    }t          j                            |          rt          j                            |          s$t	          d                    |||                    t          |          }|                    dd          }|                    t                               t%          j        |                               |                    dd          }|                    t)          j        t%          j        |                               t+          |          }	|	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 "{}"rp   Nprivate-key-ed25519r   )configparserConfigParserreadhas_sectionru   rb   
has_optionrq   rr   joindirnamerv   rs   rt   r   r   r   rf   r@   rA   r   r   )
r]   r   r   r   cfgr   rB   rw   privkey_ed25519_hexr   s
             r-   from_configz SecurityModuleMemory.from_config  s    9;'))w'' 	lRYYZacijjkkk~~gy11 	~dkklsu{||}}}',,rwv668S8STTw~~g&& 	IbgnnW.E.E 	Ifmmnuw~  AG   H   H  I  I  I
 W%% ((#4d;;K**8+;O+L+LMMNNN #hh'<dCCM,X-=>Q-R-RSSTTT "t,,,	r/   rm   c                    g }t           j                            |          rt           j                            |          s"t	          d                    |                    t          |          }|                    dd          }|"t	          d                    |                    |                    t          
                    t          j        |                               |                    dd          }|"t	          d                    |                    |                    t          j
        t          j        |                               t          |          }|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.
        ro   rp   Nz)"private-key-eth" not found in keyfile {}r   z-"private-key-ed25519" not found in keyfile {}r   )rq   rr   rs   rt   ru   rb   r   rv   r   r   rf   r@   rA   r   r   )r]   rm   r   rB   rw   r   r   s          r-   ry   z!SecurityModuleMemory.from_keyfile  sB    9;w~~g&& 	MbgnnW.E.E 	M;BB7KKLLL
 W%% ((#4d;;"JQQRYZZ[[[K**8+;O+L+LMMNNN #hh'<dCC&NUUV]^^___M,X-=>Q-R-RSSTTT "t,,,	r/   r"   )r   r   )r   )&rz   r{   r|   r}   r   r   r   r   r   r.   r   r   r~   r   r	   r   r   r   r   r   r   r   rK   r   rL   r   r   r'   r   r   r(   r   r   r   r   rl   r   ry   r5   r/   r-   r   r     s>        $ $Xd51K+L&MN $ $ $ $    $3 $4 $ $ $ $
(3-    	C# 	C%{0J*K 	C 	C 	C 	C!# !E-2L,M !RV ! ! ! !# $    1 1 11 1 1     X $    X 4    X1 1 11 1 133 33 3 3 3 3&5 5 5 5 51 1 1 1 1 1	0c 	0c 	0 	0 	0 	00C 0C 0 0 0 0 BC+,  C %(1G   [> ' ' 's 'CY ' ' ' ['R  3  +A       [     r/   r   ),r@   rq   r   collections.abcr   typingr   r   r   r   r   r	   	threadingr
   rN   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   r5   r/   r-   <module>r      s  4  				     * * * * * * = = = = = = = = = = = = = = = =         ' ' ' ' ' ' 2 2 2 2 2 2 5 5 5 5 5 5 R R R R R R R R R R R R K K K K K K K K B B B B B B B B : : : : : : ' ' ' ' ' ' 2 2 2 2 2 2
3VM VM VM VM VM& VM VM VMr  k " " "e e e e e> e e eP	  - . . . . .r/   