Fulfill the lock reward condition.

    :param event: AttributeDict with the event data.
    :param agreement_id: id of the agreement, hex str
    :param price: Asset price, int
    :param consumer_account: Account instance of the consumer
557980
def fulfill_lock_reward_condition(event, agreement_id, price, consumer_account):
    
    logger.debug(f"about to lock reward after event {event}.")
    keeper = Keeper.get_instance()
    tx_hash = None
    try:
        keeper.token.token_approve(keeper.lock_reward_condition.address, price, consumer_account)
        tx_hash = keeper.lock_reward_condition.fulfill(
            agreement_id, keeper.escrow_reward_condition.address, price, consumer_account
        )
        process_tx_receipt(
            tx_hash,
            keeper.lock_reward_condition.FULFILLED_EVENT,
            'LockRewardCondition.Fulfilled'
        )
    except Exception as e:
        logger.debug(f'error locking reward: {e}')
        if not tx_hash:
            raise e
1012518
def trade(self, trade_id, trade_price, trade_amount, trade_time):
        
        if self.status in [ORDER_STATUS.SUCCESS_PART, ORDER_STATUS.QUEUED]:
            trade_amount = int(trade_amount)
            trade_id = str(trade_id)

            if trade_amount < 1:

                self._status = ORDER_STATUS.NEXT
            else:
                if trade_id not in self.trade_id:
                    trade_price = float(trade_price)

                    trade_time = str(trade_time)

                    self.trade_id.append(trade_id)
                    self.trade_price = (
                        self.trade_price * self.trade_amount +
                        trade_price * trade_amount
                    ) / (
                        self.trade_amount + trade_amount
                    )
                    self.trade_amount += trade_amount
                    self.trade_time.append(trade_time)
                    self.callback(
                        self.code,
                        trade_id,
                        self.order_id,
                        self.realorder_id,
                        trade_price,
                        trade_amount,
                        self.towards,
                        trade_time
                    )
                else:
                    pass
        else:
            raise RuntimeError(
                'ORDER STATUS {} CANNNOT TRADE'.format(self.status)
            )
1250473
def get_event_public_discount(self, id, discount_id, **data):
        
        
        return self.get("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data)
1050727
async def put(self, public_key):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		# Check if message contains required data
		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]
		cid = int(message["offer_id"].get("cid", 0))
		buyer_address = message["offer_id"].get("buyer_address")
		coinid = message.get("coinid")

		if not all([cid, buyer_address, coinid]):
			self.set_status(400)
			self.write({"error":400, "reason": "Missed required fields."})
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])
		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coin ID"})
			raise tornado.web.Finish

		check = self.account.validator[coinid](public_key)

		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			error_code = account["error"]
			self.set_status(error_code)
			self.write(account)
			raise tornado.web.Finish
	
		# Check if one of sellers or buyers rejects offer
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		hex_ = check
		if buyer_address != hex_ and owneraddr != hex_:
			# Avoid rejecting offer
			self.set_status(403)
			self.write({"error": 403, "reason":"Forbidden. Offer does not belong to user."})
		
		# Reject offer
		response = await self.account.blockchain.rejectoffer(coinid=coinid, cid=cid, 
															buyer_address=buyer_address)
		if "error" in response.keys():
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		# Get buyer for email sending
		buyer = await self.account.getaccountbywallet(wallet=buyer_address)
		if "error" in buyer.keys():
			self.set_status(buyer["error"])
			self.write(buyer)
			raise tornado.web.Finish
	
		if buyer.get("email"):
			emaildata = {
				"to": buyer.get("email"),
				"subject": "Robin8 support",
     			"optional": "Your offer with cid %s was rejected." % cid
			}
			await self.account.mailer.sendmail(**emaildata)
		
		# Undeposit balance
		price = await self.account.blockchain.getwriteprice(cid=cid)
		coinid = "PUT"
		await self.account.balance.unfreeze(uid=buyer["id"],coinid=coinid, 
													amount=price)

		del response["result"]
		self.write(response)
715976
def get_template(self, template_id):
        
        template = self.contract_concise.getTemplate(template_id)
        if template and len(template) == 4:
            return AgreementTemplate(*template)

        return None
1102497
def on_value_event(self, event):
    
    if not event.summary.value:
      logger.info('The summary of the event lacks a value.')
      return None

    # The node name property in the event proto is actually a watch key, which
    # is a concatenation of several pieces of data.
    watch_key = event.summary.value[0].node_name
    tensor_value = debug_data.load_tensor_from_event(event)
    device_name = _extract_device_name_from_event(event)
    node_name, output_slot, debug_op = (
        event.summary.value[0].node_name.split(':'))
    maybe_base_expanded_node_name = (
        self._run_states.get_maybe_base_expanded_node_name(node_name,
                                                           self._run_key,
                                                           device_name))
    self._tensor_store.add(watch_key, tensor_value)
    self._outgoing_channel.put(_comm_tensor_data(
        device_name, node_name, maybe_base_expanded_node_name, output_slot,
        debug_op, tensor_value, event.wall_time))

    logger.info('on_value_event(): waiting for client ack (tensors)...')
    self._incoming_channel.get()
    logger.info('on_value_event(): client ack received (tensor).')

    # Determine if the particular debug watch key is in the current list of
    # breakpoints. If it is, send an EventReply() to unblock the debug op.
    if self._is_debug_node_in_breakpoints(event.summary.value[0].node_name):
      logger.info('Sending empty EventReply for breakpoint: %s',
                      event.summary.value[0].node_name)
      # TODO(cais): Support receiving and sending tensor value from front-end.
      return debug_service_pb2.EventReply()
    return None
938896
public ConsumerKey attachConsumerPoint(
    ConsumerPoint consumerPoint,
    SelectionCriteria criteria,
    SIBUuid12 connectionUuid,
    boolean readAhead,
    boolean forwardScanning,
    JSConsumerSet consumerSet) throws SIDestinationLockedException, SISelectorSyntaxException, SIDiscriminatorSyntaxException, SINotPossibleInCurrentConfigurationException, SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(this,tc, "attachConsumerPoint",
        new Object[]{consumerPoint,
                     criteria,
                     connectionUuid,
                     new Boolean(readAhead),
                     new Boolean(forwardScanning),
                     consumerSet});
    
    ConsumerKey returnKey = null;
    
    // There are a few times that we're unable to accept new consumers, e.g. forcing a
    // flush or changing cardinality. None of these events should last very long so
    // we just try again a few times, if it's still in this state then something else has
    // probably gone wrong so we bomb out. We obviously can't hold a lock while we're
    // retrying.
    int chances = 5;
    boolean repeat = true;
    while(repeat)
    {
      repeat = false;
      
      synchronized (consumerPoints)
      {
        if (!_currentReachability)
        { // don't allow an attachment if DME is not reachable or a CardinalityChange is in progress or a forced flush
          // is in progress
          // throw exception
          SIResourceException e = new SIResourceException(
            nls.getFormattedMessage("ANYCAST_STREAM_UNAVAILABLE_CWSIP0471",
                                    new Object[]{getDestName(), SIMPUtils.getMENameFromUuid(getLocalisationUuid().toString())},
                                    null));
          SibTr.exception(tc, e);
          if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "attachConsumerPoint", e);
          throw e;
        }
        else if (_cardinalityOne)
        { // enforce cardinality
          if (consumerPoints.size() != 0)
          {
            // throw exception
            SIResourceException e = new SIResourceException(
              nls.getFormattedMessage("CONSUMERCARDINALITY_LIMIT_REACHED_CWSIP0472",
                                      new Object[]{getDestName(), getLocalisationUuid().toString()},
                                      null));
            SibTr.exception(tc, e);
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
              SibTr.exit(tc, "attachConsumerPoint", e);
            throw e;
          }
        }
        // The stream is in a funny state, try again in a few milliseconds
        else if (_cardinalityChange || _forceFlushInProgress)
        {
          if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Unable to attach at this point " + _cardinalityChange + ":" +
                            _forceFlushInProgress);
          repeat = true;
        }
        
        // Work out how long we should wait for a response from the DME based on whether 
        // we are gathering or not
        long responseTimeout = 0;
        if (consumerPoint.isGatheringConsumer())
          responseTimeout = SIMPConstants.GATHERING_ANYCAST_RESPONSE_INTERVAL; // 10 seconds
        else
          responseTimeout = SIMPConstants.ANYCAST_RESPONSE_INTERVAL; // 5 minutes
        
        // do this in sync block to prevent two concurrent attachConsumerPoints from succeeding
        // when cardinalityOne, and to ensure that reachability changes are notified.
        if(_aih.consumerAttaching(responseTimeout))
        {
          returnKey = super.attachConsumerPoint(consumerPoint,
              criteria,
              connectionUuid,
              readAhead,
              forwardScanning,
              consumerSet);
        }
        else
        {
          if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Unable to attach at this point, flush work in progress");
          repeat = true;
        }

        // If we're unable to attach at this exact point, but there's a probability that
        // we will in a split second, we sleep for a short time and try again (unless it's
        // time to give up).
        if(repeat)
        {
          if(chances > 0)
          {
            try
            {
              // Release the consumerPoints lock while we're waiting
              consumerPoints.wait(100);
            }
            catch (InterruptedException e)
            {
              // No FFDC code needed
            }
            chances--;
          }
          else
          {
            // throw exception, should be rare
            SIResourceException e =
              new SIResourceException(
                nls.getFormattedMessage(
                  "ANYCAST_STREAM_NOT_FLUSHED_CWSIP0512",
                  new Object[]{_messageProcessor.getMessagingEngineName(), _destName},
                  null));
            SibTr.exception(tc, e);
            
            // As we don't expect this to have taken so long, we FFDC just in case
            // someone is interested
            FFDCFilter.processException(e,
                                        "com.ibm.ws.sib.processor.impl.RemoteConsumerDispatcher.attachConsumerPoint",
                                        "1:445:1.97.2.21",
                                        this);
            
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
              SibTr.exit(tc, "attachConsumerPoint", e);
            
            throw e;
          }
        } // repeat
      } // end synchronized (consumerPoints)
    } // while
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "attachConsumerPoint", returnKey);
    return returnKey;
  }
327651
async def post(self, public_key):
		
		logging.debug("[+] -- Deal debugging. ")
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		# Check if message contains required data
		try:
			body = json.loads(self.request.body)
		except:
			self.set_status(400)
			self.write({"error":400, "reason":"Unexpected data format. JSON required"})
			raise tornado.web.Finish
		logging.debug("\n         Body")
		logging.debug(body)
			
		if isinstance(body["message"], str):
			message = json.loads(body["message"])
		elif isinstance(body["message"], dict):
			message = body["message"]

		cid = message.get("cid")
		buyer_pubkey = message.get("buyer_pubkey")
		buyer_access_string = message.get("buyer_access_string")

		seller_access_string = message.get("seller_access_string")
		access_type = message.get("access_type")

		coinid = message.get("coinid")
		# check passes data
		if not all([buyer_access_string, cid, buyer_pubkey, coinid]):
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields"})
			raise tornado.web.Finish

		if coinid in settings.bridges.keys():
			self.account.blockchain.setendpoint(settings.bridges[coinid])

		else:
			self.set_status(400)
			self.write({"error":400, "reason":"Invalid coin ID"})
			raise tornado.web.Finish 

		# Sellcontent
		buyer_address = self.account.validator[coinid](buyer_pubkey)

		# Check if accounts exists
		seller_account = await self.account.getaccountdata(public_key=public_key)
		logging.debug("\n          Seller account")
		logging.debug(seller_account)

		try:
			error_code = seller_account["error"]
		except:
			pass
		else:
			self.set_status(error_code)
			self.write(seller_account)
			raise tornado.web.Finish

		buyer_account = await self.account.getaccountdata(public_key=buyer_pubkey)
		logging.debug("\n           Buyer account")
		logging.debug(buyer_account)
		try:
			error_code = buyer_account["error"]
		except:
			pass
		else:
			self.set_status(error_code)
			self.write(buyer_account)
			raise tornado.web.Finish

		# Check if content belongs to current account
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)
		
		
		if owneraddr != self.account.validator[coinid](public_key):
			self.set_status(403)
			self.write({"error":403, "reason":"Forbidden. Profile owner does not match."})
			raise tornado.web.Finish

		#Get buyers balance
		balances = await self.account.balance.get_wallets(coinid=coinid, 
														uid=buyer_account["id"])
		if isinstance(balances, dict):
			if "error" in balances.keys():
				self.set_status(balances["error"])
				self.write(balances)
				raise tornado.web.Finish 


		# Get difference with balance and price
		get_price = await self.account.blockchain.getoffer(buyer_address=buyer_address,
															cid=cid)
		price = get_price["price"]
		logging.debug("\n          Price")
		logging.debug(price)

		for w in balances["wallets"]:
			if "PUT" in w.values() or "PUTTEST" in w.values():
				balance = w

		difference = int(balance["amount_frozen"]) - int(price)

		if difference >= 0:

			if access_type == "write_access":
				logging.debug("\n          Write access")
				# Fee
				fee = await billing.change_owner_fee(cid=cid, new_owner=buyer_pubkey)
				if "error" in fee.keys():
					self.set_status(fee["error"])
					self.write(fee)
					raise tornado.web.Finish
			
				# Change content owner
				chownerdata = {
					"cid":cid,
					"new_owner": buyer_address,
					"access_string": buyer_access_string,
					"seller_public_key": public_key
				}

				response = await self.account.blockchain.changeowner(**chownerdata)
				logging.debug("\n         Bridge change owner")
				logging.debug(response)

				new_owner = await self.account.changeowner(cid=cid, 
										public_key=buyer_account["public_key"], 
										coinid=coinid)
				logging.debug("\n Database new owner")
				logging.debug(new_owner)

			elif access_type == "read_access":
				logging.debug("\n          Read access")

				# Fee
				fee = await billing.sell_content_fee(cid=cid, new_owner=buyer_pubkey)

				if "error" in fee.keys():
					self.set_status(fee["error"])
					self.write(fee)
					raise tornado.web.Finish

				selldata = {
					"cid":cid,
					"buyer_address":buyer_address,
					"access_string":buyer_access_string,
					"seller_public_key":public_key
				}

				response = await self.account.blockchain.sellcontent(**selldata)
				logging.debug("\n        Bridge sell content")

				# Write cid to database
				check = await self.account.setuserscontent(public_key=buyer_account["public_key"], 
											hash=None,coinid=coinid, cid=cid,
											txid=response["result"]["txid"],
											access="deal")
				logging.debug(check)

			
			# Increment and decrement balances of seller and buyer
			coinid = "PUT"
			unfreeze = await self.account.balance.unfreeze(uid=buyer_account["id"],
													amount=price, coinid=coinid)
			logging.debug("\n          Unfreeze buyer")
			logging.debug(unfreeze)

			sub_active = await self.account.balance.sub_active(uid=buyer_account["id"], 
												coinid=coinid, amount=price)
			logging.debug("\n            Sub active")
			logging.debug(sub_active)
			add_frozen = await self.account.balance.add_frozen(uid=seller_account["id"], 
												amount=price, coinid=coinid)
			logging.debug("\n               Add frozen")
			logging.debug(add_frozen)
			# Write entry with txid to database
			new_deal = await self.account.balance.registerdeal(uid=seller_account["id"],
													public_key=seller_account["public_key"], 
													txid=response["result"]["txid"],
													coinid=coinid, cid=cid)

			del response["result"]
			del response["contract_owner_hex"]
			self.write(response)
		else:
			# If Insufficient funds
			self.set_status(402)
			self.write({"error":402, "reason":"Insufficient funds of buyer"})
			raise tornado.web.Finish
1200573
def sync_account(self, sync_message):
        

        self.init_hold = sync_message['hold_available']
        self.init_cash = sync_message['cash_available']

        self.sell_available = copy.deepcopy(self.init_hold)
        self.history = []
        self.cash = [self.init_cash]
        self.cash_available = self.cash[-1]
607686
def generate_id(self, agreement_id, types, values):
        
        values_hash = utils.generate_multi_value_hash(types, values)
        return utils.generate_multi_value_hash(
            ['bytes32', 'address', 'bytes32'],
            [agreement_id, self.address, values_hash]
        )
1360807
def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server):
        '''
        '''
        raise NotImplementedError("Logging Handler must implement event_payment")
1225712
async def get(self, public_key):
		
		# Sign-verifying functional
		#super().verify()
		# Get coinid
		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			self.set_status(account["error"])
			self.write(account)
			raise tornado.web.Finish



		offers_collection = []
		for coinid in settings.AVAILABLE_COIN_ID:

			try:
				self.account.blockchain.setendpoint(settings.bridges[coinid])
			except:
				continue

			try:
				offers = await self.account.blockchain.getbuyeroffers( 
								buyer_address=self.account.validator[coinid](public_key))
				for offer in offers:
					offer["type"] = self.account.ident_offer[offer["type"]]
	
				storage_offers = await self.account.getoffers(coinid=coinid, 
																public_key=public_key)

			except:
				continue

			offers_collection.extend(offers + storage_offers)


		self.write(json.dumps(offers_collection))
258681
def wait_for_transfer_success(
        raiden: 'RaidenService',
        payment_identifier: PaymentID,
        amount: PaymentAmount,
        retry_timeout: float,
) -> None:
    
    found = False
    while not found:
        state_events = raiden.wal.storage.get_events()
        for event in state_events:
            found = (
                isinstance(event, EventPaymentReceivedSuccess) and
                event.identifier == payment_identifier and
                event.amount == amount
            )
            if found:
                break

        gevent.sleep(retry_timeout)
886092
def settle(
            self,
            transferred_amount: TokenAmount,
            locked_amount: TokenAmount,
            locksroot: Locksroot,
            partner_transferred_amount: TokenAmount,
            partner_locked_amount: TokenAmount,
            partner_locksroot: Locksroot,
            block_identifier: BlockSpecification,
    ):
        
        self.token_network.settle(
            channel_identifier=self.channel_identifier,
            transferred_amount=transferred_amount,
            locked_amount=locked_amount,
            locksroot=locksroot,
            partner=self.participant2,
            partner_transferred_amount=partner_transferred_amount,
            partner_locked_amount=partner_locked_amount,
            partner_locksroot=partner_locksroot,
            given_block_identifier=block_identifier,
        )
214415
def propose_value(self, key, value, assume_leader=False):
        
        assert isinstance(key, UUID)
        paxos_aggregate = PaxosAggregate.start(
            originator_id=key,
            quorum_size=self.quorum_size,
            network_uid=self.name
        )
        msg = paxos_aggregate.propose_value(value, assume_leader=assume_leader)
        while msg:
            msg = paxos_aggregate.receive_message(msg)
        new_events = paxos_aggregate.__batch_pending_events__()
        self.record_process_event(ProcessEvent(new_events))
        self.repository.take_snapshot(paxos_aggregate.id)
        self.publish_prompt()
        return paxos_aggregate
981335
def post_event_public_discount(self, id, discount_id, **data):
        
        
        return self.post("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data)
1280826
def ack(self, id, transaction=None, receipt=None):
        
        assert id is not None, "'id' is required"
        headers = {HDR_MESSAGE_ID: id}
        if transaction:
            headers[HDR_TRANSACTION] = transaction
        if receipt:
            headers[HDR_RECEIPT] = receipt
        self.send_frame(CMD_ACK, headers)