o
    >h	m                     @   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 dd	l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hlval)sign_eip712_channel_closerecover_eip712_channel_closec                   @   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/vedio/testing/chatpythonscript.ninositsolution.com/env/lib/python3.10/site-packages/autobahn/xbr/_buyer.py__init__3   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__J   s   zTransaction.__str__N)__name__
__module____qualname__r   r   r   r   r   r   r   r   1   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 | _|| _d| _	|| _
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_xbrmm_config	_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   U   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 zR|dI dH | _t| jtkrJt| jdksLJ |d| jI dH | _| js^td	| jd
 }t|tkrot|dksqJ tj|d| _|d| jjI dH }W n   |   t|d tkrt|d |d< |d dkstd|d | _|d | _| jjdt| jt| jt| 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
   )addressr6   zxbr.marketmaker.get_configr$   z*xbr.marketmaker.get_active_payment_channelzno active payment channel foundchannel_oid   r'   +xbr.marketmaker.get_payment_channel_balance	remainingr   z1no off-chain balance remaining on payment channelseqzvOk, buyer delegate started [active payment channel {channel_oid} with remaining balance {remaining} at sequence {seq}])rM   rQ   rR   )
isinstancer   r&   strrD   rC   r-   debugr	   r9   binasciib2a_hexr4   r6   decodecallr/   r8   r'   r(   r?   	ExceptionuuidUUID_channel_oidleaver   r@   rA   infor
   )r   sessionconsumer_idrM   payment_balancer   r   r   start   sB   
 


zSimpleBuyer.startc                    s"   | j sJ d| _ | jd dS )z#
        Stop buying keys.
        FzOk, buyer delegate stopped.N)rD   r-   r_   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
        rP   rM   N)rC   is_attachedrY   r?   )r   rb   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   rQ   inflight)r   rQ   rg   )rC   re   osurandomrY   r8   )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   rk   r   r   r   close_channel  s    zSimpleBuyer.close_channelc           $         s  t |tkrt|dksJ t |tkr|dv sJ t |tks#J | jd }| jd }d}| jd }t| jd dd	 }|| jv rU| j	j
d
ttj|dd np| 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 r3| jrd	}|  }|r|d }|r| j}| j}d}t| j||||||||	}| j	j
dtj|d|t|d |d | jd||||t||||	I d	H  tdd| jjtj|d|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||||||||	}| $|| j%||||
|| z| jd | j%||||t|
t||	I d	H }W n7 ty } z|j&dkr| '  |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rtd+d,| jj| j|d# | j|
 |kr/td+d-| jj| j|
 |d% || _|| _| /|| j+|||||| |d. }t!j01| j}z|2|}W n t!j3j4ys } z|| j|< td/d0| jj|d	}~ww t!j56|| j|< | 7 } | j	j8d1| jjtd2d3d4ttj|dttt|d d5 d3d4tt-|d6 . tt|d tt|d tt-|. | d7
 d}!| j| du r|!d8 r| j	j
d9| jjttj|dd: |!d7 }!t9:d;I d	H  | j| du st;| j| t(r	| j| }|z
| j| 2|}"W n t!j3j4y- } ztd/d<| jj|d	}~ww zt<=|"}#W |#S  t<j>j?yP } 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
        rN   )cbor
market_oidrM   r   verifying_chain_idverifying_contract_adrr   Nz>Key {key_id} already in key store (or currently being bought).rO   )r   z1Key {key_id} not yet in key store - buying key ..Fzxbr.marketmaker.get_quote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 {channel_oid} [close_seq={close_seq}, close_balance={close_balance}, close_is_final={close_is_final}])rM   	close_seqclose_balanceclose_is_finalzxbr.marketmaker.close_channelzxbr.error.channel_closedzu{}.unwrap() - key {} cannot be bought: payment channel {} 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 {})encoderzxbr.marketmaker.buy_keyz8Encountered error while calling market maker to buy key!r   r   amount_paidrQ   rg   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 XBRrl   )	ry   tx_typer   rx   rl   rQ   rg   buyer_pubkeytransactionsd   zG{klass}.unwrap() - waiting for key "{key_id}" currently being bought ..)ry   r   g?z1{}.unwrap() - failed to unwrap encrypted data: {}z xbr.error.deserialization_failedz;{}.unwrap() - failed to deserialize application payload: {})@r&   r'   r(   rT   r?   r/   rV   a2b_hexrB   r-   rU   r	   r[   r\   rC   rY   r   r*   r>   r   r)   	__class__r    r@   rE   past_transactionsrA   r   r0   r   r=   r6   encoder:   encoding
RawEncoder_save_transaction_phase1r8   errorrd   rZ   failurer   r.   warnrW   rX   _save_transaction_phase2r;   	SealedBoxdecrypt
exceptionsCryptoErrorsecret	SecretBoxcount_transactionsr_   r+   sleeprS   cbor2loadsdecoderCBORDecodeError)$r   r   
serializer
ciphertextrp   rM   current_block_numberrq   rr   quoter   r   last_txtxnsrt   ru   rv   r   r   r   is_finalreceiptemarketmaker_signaturemarketmaker_channel_seqmarketmaker_amount_paidmarketmaker_remainingmarketmaker_inflightrz   r|   
unseal_boxkeytransactions_countlog_countermessagepayloadr   r   r   unwrap  st  






,













	





zSimpleBuyer.unwrapc	              	   C   s\   || j v rtdt|t||||||||}	t| j}
| j|	dg |
| j |< dS )

        :param channel_oid:
        :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)	rF   RuntimeErrorr)   rV   rW   r   r(   rG   append)r   rM   r{   r   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)rF   r   r)   rV   rW   rG   r   r   r   r   r   r   r   r   )r   rM   r{   r   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(   rG   r   )r   filter_completelimitnr   txr   r   r   r   B  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   )rG   )r   r   r   r   r   r   r   r   X  s   zSimpleBuyer.count_transactionsc                 C   s    | j |d}|r| j| S dS )2

        :param key_id:
        :return:
        NrF   getrG   )r   r   idxr   r   r   get_transactionh  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_completer  s
   zSimpleBuyer.is_completer   )Tr   )r    r!   r"   __doc__r-   r   rc   rd   r   rm   rn   r   r   r   r   r   r   r   r   r   r   r   r#   N   s"    E:


 r
&
r#   )r[   rV   pprintr   rh   r   nacl.secretr:   
nacl.utilsnacl.exceptionsnacl.publicr+   autobahn.wamp.exceptionr   autobahn.wamp.protocolr   _utilr   r   r1   utilr	   r
   _eip712_channel_closer   r   objectr   r#   r   r   r   r   <module>   s$   