o
    @Bi5d                     @   s   d dl Z d dlZd dlmZ d dlZd dlZd dlZd dlZd dl	Zd dl
Zd dlZd dlmZ d dlmZ ddlmZmZ d dlZddlmZmZmZ G dd	 d	eZG d
d deZdS )    N)pformat)ApplicationError)ApplicationSession   )unpack_uint256pack_uint256)hlsign_eip712_datarecover_eip712_signerc                   @   s$   e Zd Zdd Zdd Zdd ZdS )Transactionc	           	      C   s4   || _ || _|| _|| _|| _|| _|| _|| _d S Nchanneldelegatepubkeykey_idchannel_seqamountbalance	signature)	selfr   r   r   r   r   r   r   r    r   S/var/www/html/Trade-python/venv/lib/python3.10/site-packages/autobahn/xbr/_buyer.py__init__4   s   
zTransaction.__init__c              	   C   s*   | j | j| j| j| j| j| j| jd}|S )Nr   r   )r   resr   r   r   marshal>   s   
zTransaction.marshalc                 C   s   t |  S r   )r   r   r   r   r   r   __str__K   s   zTransaction.__str__N)__name__
__module____qualname__r   r   r   r   r   r   r   r   2   s    
r   c                   @   s   e Zd ZdZdZdd Zdd Zdd Zd	d
 ZdddZ	dddZ
dd Zdd Zdd Zd ddZdd Zdd Zdd ZdS )!SimpleBuyerz
    Simple XBR buyer component. This component can be used by a XBR buyer delegate to
    handle the automated buying of data encryption keys from the XBR market maker.
    Nc                 C   s   t |tkrt|dksJ d|t |tkrt|dks&J d|t |tkr0|dks2J t | _|| _|| _	t
j|| _d| _| jj | _d| _tjj | _|| _d| _d| _d| _i | _d| _d| _d| _i | _g | _ dS )	a  

        :param market_maker_adr:
        :type market_maker_adr:

        :param buyer_key: Consumer delegate (buyer) private Ethereum key.
        :type buyer_key: bytes

        :param max_price: Maximum price we are willing to buy per key.
        :type max_price: int
           z0market_maker_adr must be bytes[20], but got "{}"    z.buyer delegate must be bytes[32], but got "{}"r   NFT)!typebyteslenformatinttxaiomake_loggerlog_market_maker_adr	_pkey_raweth_keyskeys
PrivateKey_pkey_acct
public_keyto_canonical_address_addr_caddrnaclpublicgenerate_receive_key
_max_price_channel_balance_seq_keys_session_running_auto_close_channel_transaction_idx_transactions)r   market_maker_adr	buyer_key	max_pricer   r   r   r   V   s*   &&

zSimpleBuyer.__init__c                    s,  t |tsJ t|tksJ | jrJ || _d| _| jjdt| j	t
| jjdd  d z)t| jtkrAt| jdksCJ |d| jI dH | _|d| jd	 I dH }W n   |   |d
 | _t| jtkrvt| j| _|d | _| jjdtdt
| jd	   | j| jd | jS )a  
        Start buying keys to decrypt XBR data by calling ``unwrap()``.

        :param session: WAMP session over which to communicate with the XBR market maker.
        :type session: :class:`autobahn.wamp.protocol.ApplicationSession`

        :param consumer_id: XBR consumer ID.
        :type consumer_id: str

        :return: Current remaining balance in payment channel.
        :rtype: int
        TzSStart buying from consumer delegate address {address} (public key 0x{public_key}..)N
   )addressr3   r"   z*xbr.marketmaker.get_active_payment_channel+xbr.marketmaker.get_payment_channel_balancer   	remainingseqztDelegate has current payment channel address {payment_channel_adr} (remaining balance {remaining} at sequence {seq})0x)payment_channel_adrrK   rL   )
isinstancer   r$   strrA   r@   r+   infor   r6   binasciib2a_hexr1   r3   decoder5   r%   r&   callr<   leaver=   r   r>   )r   sessionconsumer_idpayment_balancer   r   r   start   s4   
 

zSimpleBuyer.startc                    s   | j sJ d| _ dS )z#
        Stop buying keys.
        FN)rA   r   r   r   r   stop   s   

zSimpleBuyer.stopc                    s4   | j r	| j  sJ | j d| jd I dH }|S )a  
        Return current balance of payment channel:

        * ``amount``: The initial amount with which the payment channel was opened.
        * ``remaining``: The remaining amount of XBR in the payment channel that can be spent.
        * ``inflight``: The amount of XBR allocated to buy transactions that are currently processed.

        :return: Current payment balance.
        :rtype: dict
        rJ   r   N)r@   is_attachedrU   r<   )r   rY   r   r   r   r      s   zSimpleBuyer.balancec                    sX   | j r	| j  sJ td}| j d|| j||I dH }|d |d |d d}|S )z

        :param amount:
        :type amount:

        :param details:
        :type details:

        :return:
        :rtype:
        @   z$xbr.marketmaker.open_payment_channelNr   rK   inflight)r   rK   r^   )r@   r\   osurandomrU   r5   )r   
buyer_addrr   detailsr   payment_channelr   r   r   r   open_channel   s   

zSimpleBuyer.open_channelc                    s   dS )z[
        Requests to close the currently active payment channel.

        :return:
        Nr   )r   rb   r   r   r   close_channel  s    zSimpleBuyer.close_channelc           !         sj  t |tkrt|dksJ t |tkr|dv sJ t |tks#J t| jd }|| jv r?| jjdtt	j
|dd nj| jjdtt	j
|dd d| j|< | jd	|I d
H }t|d }| jjdtt	j
|dtt|d d || jkrtdd| jjt	j
|dt|d t| jd | j| }|dk r| jrd
}|  }	|	r|	d }|r|}
| j}| j}d}t| j|
|||}| jjdt|
 |t|d |d | jd|
|t|||I d
H  tdd| jjt	j
|dt|
 t|d tdd| jjt	j
|dt| jd t|d | jjj t!j"j#d}| jd }d}t| j||||d}| $|| j%|||||| z| jd| j%||||t|t||	I d
H }W n7 tyw } z|j&dkrq| '  |d
}~w t(y } z| j&d | j)  || j|< |d
}~ww |d }|d  }t|d! }t|d" }t|d# }t*|||d|}|| j+kr| jj,d$| jjtt| tt| j+ d% td&d'| jj| jd |krtd(d)| jj| j|d  | j| |krtd(d*| jj| j| |d" || _|| _| -|| j+|||||| |d+ }t!j./| j}z|0|}W n t!j1j2yW } z|| j|< td,d-| jj|d
}~ww t!j34|| j|< | 5 }| jjd.| jjtd/d0d1tt	j
|dttt|d d2 d0d1tt|d3  tt|d tt|d tt| |d4
 d}| j| du r|d5 r| jjd6| jjtt	j
|dd7 |d7 }t67d8I d
H  | j| du st8| j| t(r| j| }|z
| j| 0|}W n t!j1j2y } ztd,d9| jj|d
}~ww zt9:|} W | S  t9j;j<y4 } ztd:d;| jj|d
}~ww )<aO  
        Decrypt XBR data. This functions will potentially make the buyer call the
        XBR market maker to buy data encryption keys from the XBR provider.

        :param key_id: ID of the data encryption used for decryption
            of application payload.
        :type key_id: bytes

        :param serializer: Application payload serializer.
        :type serializer: str

        :param ciphertext: Ciphertext of encrypted application payload to
            decrypt.
        :type ciphertext: bytes

        :return: Decrypted application payload.
        :rtype: object
           )cborr   z>Key {key_id} already in key store (or currently being bought).)r%   )r   z1Key {key_id} not yet in key store - buying key ..Fzxbr.marketmaker.get_quoteNpricez-Key {key_id} has current price quote {amount}l     NZo)r   r   zxbr.error.max_price_exceededzR{}.unwrap() - key {} needed cannot be bought: price {} exceeds maximum price of {}r   Tzauto-closing payment channel {close_adr} [close_seq={close_seq}, close_balance={close_balance}, close_is_final={close_is_final}])	close_adr	close_seqclose_balanceclose_is_finalzxbr.marketmaker.close_channelzxbr.error.channel_closedzw{}.unwrap() - key {} cannot be bought: payment channel 0x{} ran empty and we initiated close at remaining balance of {}zxbr.error.insufficient_balancez_{}.unwrap() - key {} cannot be bought: insufficient balance {} in payment channel for amount {})encoderr   )is_finalzxbr.marketmaker.buy_keyz8Encountered error while calling market maker to buy key!r   r   amount_paidrK   r^   zv{klass}.unwrap()::XBRSIG[8/8] - EIP712 signature invalid: signer_address={signer_address}, delegate_adr={delegate_adr})klasssigner_addressdelegate_adrzxbr.error.invalid_signaturezQ{}.unwrap()::XBRSIG[8/8] - EIP712 signature invalid or not signed by market makerzxbr.error.invalid_transactionz^{}.buy_key(): invalid transaction (channel sequence number mismatch - expected {}, but got {})z_{}.buy_key(): invalid transaction (channel remaining amount mismatch - expected {}, but got {})
sealed_keyzxbr.error.decryption_failedz6{}.unwrap() - could not unseal data encryption key: {}z{klass}.unwrap() - {tx_type} key {key_id} bought for {amount_paid} [payment_channel={payment_channel}, remaining={remaining}, inflight={inflight}, buyer_pubkey={buyer_pubkey}, transactions={transactions}]z
XBR BUY   magenta)colorz XBRrc   )	rp   tx_typer   ro   rc   rK   r^   buyer_pubkeytransactionsd   zG{klass}.unwrap() - waiting for key "{key_id}" currently being bought ..)rp   r   g?z1{}.unwrap() - failed to unwrap encrypted data: {}z xbr.error.deserialization_failedz;{}.unwrap() - failed to deserialize application payload: {})=r$   r%   r&   rP   r<   r?   r+   rQ   r   uuidUUIDr@   rU   r   r(   r;   r   r'   	__class__r   r=   rB   past_transactionsr>   r	   r-   rR   rS   rT   r   r:   r3   encoder7   encoding
RawEncoder_save_transaction_phase1r5   errorr[   	Exceptionfailurer
   r,   warn_save_transaction_phase2r8   	SealedBoxdecrypt
exceptionsCryptoErrorsecret	SecretBoxcount_transactionsr)   sleeprO   cbor2loadsdecoderCBORDecodeError)!r   r   
serializer
ciphertextchannel_adrquoter   r   last_txtxnsri   rj   rk   rl   r   rw   r   rn   receiptemarketmaker_signaturemarketmaker_channel_seqmarketmaker_amount_paidmarketmaker_remainingmarketmaker_inflightrq   rs   
unseal_boxkeytransactions_countlog_countermessagepayloadr   r   r   unwrap	  s<  



,


 






	





zSimpleBuyer.unwrapc	              	   C   s\   || j v rtdt|t||||||||}	t| j}
| j|	dg |
| j |< dS )

        :param channel_adr:
        :param delegate_adr:
        :param buyer_pubkey:
        :param key_id:
        :param channel_seq:
        :param amount:
        :param balance:
        :param signature:
        :return:
        z;save_transaction_phase1: duplicate transaction for key 0x{}N)	rC   RuntimeErrorr'   rR   rS   r   r&   rD   append)r   r   rr   rw   r   r   r   r   r   tx1key_idxr   r   r   r     s   

z$SimpleBuyer._save_transaction_phase1c	              	   C   s   || j vrtdt|| j | }	| j|	 d r%tdt|| j|	 d }
t||||||||}|
j|jks?J |
j|jksGJ |
j	|j	ksOJ |
j
|j
ksWJ |
j|jks_J |
j|jksgJ |
j|jksoJ || j|	 d< dS )r   z;save_transaction_phase2: transaction for key 0x{} not foundr   z;save_transaction_phase2: duplicate transaction for key 0x{}r   N)rC   r   r'   rR   rS   rD   r   r   r   r   r   r   r   r   )r   r   rr   rw   r   r   r   r   r   r   r   tx2r   r   r   r     s"   

z$SimpleBuyer._save_transaction_phase2Tr   c                 C   s   t |tksJ t |tkr|dksJ d}g }||k rDt| j|kr=| j|  }|r3|d r<|d r<|| |d7 }n	 |S ||k s|S )zQ

        :param filter_complete:
        :param limit:
        :return:
        r   r   )r$   boolr(   r&   rD   r   )r   filter_completelimitnr   txr   r   r   r}     s   
zSimpleBuyer.past_transactionsc                 C   sH   ddd}| j D ]\}}|r|r|d  d7  < q|d  d7  < q|S )z

        :return:
        r   )completependingr   r   r   )rD   )r   r   r   r   r   r   r   r   2  s   zSimpleBuyer.count_transactionsc                 C   s    | j |d}|r| j| S dS )2

        :param key_id:
        :return:
        NrC   getrD   )r   r   idxr   r   r   get_transactionB  s   
zSimpleBuyer.get_transactionc                 C   s,   | j |d}|r| j| \}}|o|S dS )r   NFr   )r   r   r   r   r   r   r   r   is_completeL  s
   zSimpleBuyer.is_completer   )Tr   )r   r   r    __doc__r+   r   rZ   r[   r   rd   re   r   r   r   r}   r   r   r   r   r   r   r   r!   O   s"    D0

 X
&
r!   )rz   rR   pprintr   r_   r   nacl.secretr7   
nacl.utilsnacl.exceptionsnacl.publicr)   autobahn.wamp.exceptionr   autobahn.wamp.protocolr   _utilr   r   r.   r   r	   r
   objectr   r!   r   r   r   r   <module>   s"   