Find a transaction on the distributed ledger by its sequence number.

        :param txn: transaction number
        :return: json sequence number of transaction, null for no match
18970
async def get_txn(self, txn: int) -> str:
        

        LOGGER.debug('_BaseAgent.get_txn >>> txn: %s', txn)

        rv_json = json.dumps({})
        req_json = await ledger.build_get_txn_request(self.did, None, txn)
        resp = json.loads(await self._submit(req_json))

        rv_json = json.dumps((resp['result'].get('data', {}) or {}).get('txn', {}))  # "data": null for no such txn
        LOGGER.debug('_BaseAgent.get_txn <<< %s', rv_json)
        return rv_json
224396
def transform_txn_for_ledger(txn):
        '''
        
        '''
        txn_data = get_payload_data(txn)
        txn_data[AUDIT_TXN_LEDGERS_SIZE] = {int(k): v for k, v in txn_data[AUDIT_TXN_LEDGERS_SIZE].items()}
        txn_data[AUDIT_TXN_LEDGER_ROOT] = {int(k): v for k, v in txn_data[AUDIT_TXN_LEDGER_ROOT].items()}
        txn_data[AUDIT_TXN_STATE_ROOT] = {int(k): v for k, v in txn_data[AUDIT_TXN_STATE_ROOT].items()}
        return txn
266484
def check_tx(self, tx) -> ResponseCheckTx:
        
        value = decode_number(tx)
        if not value == (self.txCount + 1):
            # respond with non-zero code
            return ResponseCheckTx(code=1)
        return ResponseCheckTx(code=CodeTypeOk)
984228
def txn(self, read_only=False, best_effort=False):
        """"""
        return txn.Txn(self, read_only=read_only, best_effort=best_effort)
797960
def get_unconfirmed_tx(api_code=None):
    

    resource = 'unconfirmed-transactions?format=json'
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = util.call_api(resource)
    json_response = json.loads(response)
    return [Transaction(t) for t in json_response['txs']]
1030210
def eth_getBlockTransactionCountByNumber(self, block=BLOCK_TAG_LATEST):
        
        block = validate_block(block)
        return hex_to_dec((yield from self.rpc_call('eth_getBlockTransactionCountByNumber',
                                                    [block])))
912855
def check_tx(self, raw_transaction):
        

        self.abort_if_abci_chain_is_not_synced()

        logger.debug('check_tx: %s', raw_transaction)
        transaction = decode_transaction(raw_transaction)
        if self.bigchaindb.is_valid_transaction(transaction):
            logger.debug('check_tx: VALID')
            return ResponseCheckTx(code=CodeTypeOk)
        else:
            logger.debug('check_tx: INVALID')
            return ResponseCheckTx(code=CodeTypeError)
102399
def get_transactions_details(tx_hash_list, coin_symbol='btc', limit=None, api_key=None):
    

    for tx_hash in tx_hash_list:
        assert is_valid_hash(tx_hash)
    assert is_valid_coin_symbol(coin_symbol)

    if len(tx_hash_list) == 0:
        return []
    elif len(tx_hash_list) == 1:
        return [get_transaction_details(tx_hash=tx_hash_list[0],
                                        coin_symbol=coin_symbol,
                                        limit=limit,
                                        api_key=api_key
                                        )]

        url = make_url(coin_symbol, **dict(txs=';'.join(tx_hash_list)))

    params = {}
    if api_key:
        params['token'] = api_key
    if limit:
        params['limit'] = limit

    r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict_list = get_valid_json(r)

    cleaned_dict_list = []

    for response_dict in response_dict_list:
        if 'error' not in response_dict:
            if response_dict['block_height'] > 0:
                response_dict['confirmed'] = parser.parse(response_dict['confirmed'])
            else:
                # Blockcypher reports fake times if it's not in a block
                response_dict['confirmed'] = None
                response_dict['block_height'] = None

            # format this string as a datetime object
            response_dict['received'] = parser.parse(response_dict['received'])
        cleaned_dict_list.append(response_dict)

    return cleaned_dict_list
539293
private int transactionToIndex(T t) {
		Integer r = allTransactions.absoluteIndexOf(t);
		return r == null ? -1 : r.intValue();
	}
401167
def tx_for_tx_hash(self, tx_hash):
        ""
        url = self.base_url("get_tx", b2h_rev(tx_hash))
        r = json.loads(urlopen(url).read().decode("utf8"))
        tx = Tx.parse(io.BytesIO(h2b(r.get("data").get("tx_hex"))))
        return tx
309525
async def push_transaction_async(self):
        
        await self.connect_async(loop=self.loop)
        depth = self.transaction_depth_async()
        if not depth:
            conn = await self._async_conn.acquire()
            self._task_data.set('conn', conn)
        self._task_data.set('depth', depth + 1)
1074550
def get_next_occurrence(tx: ScheduledTransaction) -> date:
    
    # Reference documentation:
    # https://github.com/MisterY/gnucash-portfolio/issues/3

    # Preparing ref day is an important part before the calculation.
    # It should be:
    #   a) the last occurrence date + 1, or
    #   b) the recurrence start date - 1.
    # because the refDate is the date from which the due dates are being calculated. To include
    # the ones starting today, we need to calculate from the day before.
    ref_datum: Datum = Datum()
    if tx.last_occur:
        #ref_datum.set_value(tx.last_occur)
        ref_datum.from_date(tx.last_occur)
        ref_datum.add_days(1)
    else:
        ref_datum.from_date(tx.recurrence.recurrence_period_start)
        ref_datum.subtract_days(1)
    ref_date: datetime = ref_datum.value

    # today = datetimeutils.today_date()
    #today = Datum().today()
    # skipped schedule
    #if ref_date > today: 
    #    ref_date = today

    ###########################################################
    # The code below mimics the function
    # recurrenceNextInstance(const Recurrence *r, const GDate *refDate, GDate *nextDate)
    # https://github.com/Gnucash/gnucash/blob/115c0bf4a4afcae4269fe4b9d1e4a73ec7762ec6/libgnucash/engine/Recurrence.c#L172

    start_date: Datum = Datum()
    #start_date: datetime = tx.recurrence.recurrence_period_start
    start_date.from_date(tx.recurrence.recurrence_period_start)
    if ref_date < start_date.value:
        # If the occurrence hasn't even started, the next date is the start date.
        # this should also handle the "once" type in most cases.
        return start_date.value.date()

    # start at refDate.
    next_date: Datum = Datum()
    # next_date: datetime = ref_date
    next_date.from_datetime(ref_date)

    # last_date: datetime = tx.last_occur
    # print(tx.name, base_date, tx.recurrence.recurrence_period_start,
    #       tx.recurrence.recurrence_mult, tx.recurrence.recurrence_period_type)

    # /* Step 1: move FORWARD one period, passing exactly one occurrence. */

    mult: int = tx.recurrence.recurrence_mult
    period: str = tx.recurrence.recurrence_period_type
    wadj = tx.recurrence.recurrence_weekend_adjust

    # Not all periods from the original file are included at the moment.
    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        if period == RecurrencePeriod.YEAR.value:
            mult *= 12

        # handle weekend adjustment here.
        ## Takes care of short months.
        # next_weekday = datetimeutils.get_day_name(next_date)
        next_weekday = next_date.get_day_name()
        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and
                (next_weekday == "Saturday" or next_weekday == "Sunday")):
            # "Allows the following Friday-based calculations to proceed if 'next'
            #  is between Friday and the target day."
            days_to_subtract = 1 if next_weekday == "Saturday" else 2

            # next_date = datetimeutils.subtract_days(next_date, days_to_subtract)
            next_date.subtract_days(days_to_subtract)

        if wadj == WeekendAdjustment.BACK.value and (
                period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                            RecurrencePeriod.END_OF_MONTH.value]) and next_weekday == "Friday"):
            next_date = handle_friday(next_date, period, mult, start_date)

        # Line 274.
        temp_date = next_date.clone()
        if (temp_date.is_end_of_month() or
                (period in [RecurrencePeriod.MONTH.value, RecurrencePeriod.YEAR.value]
                 and (next_date.get_day() >= start_date.get_day()))
           ):
            # next_date = datetimeutils.add_months(next_date, mult)
            next_date.add_months(mult)
            # Set at end of month again (?!)
            #next_date = datetimeutils.get_end_of_month(next_date)
        else:
            # one fewer month fwd because of the occurrence in this month.
            next_date.add_months(mult - 1)

    # elif period == "once":
    #     next_date = tx.recurrence.recurrence_period_start

    elif period == RecurrencePeriod.DAY.value:
        logging.warning("daily not handled")

    else:
        logging.info(f"recurrence not handled: {period}")

    #######################
    # Step 2
    # "Back up to align to the base phase. To ensure forward
    # progress, we never subtract as much as we added (x % mult < mult)"

    if period in ([RecurrencePeriod.YEAR.value, RecurrencePeriod.MONTH.value,
                   RecurrencePeriod.END_OF_MONTH.value]):
        n_months = (
            12 * (next_date.get_year() - start_date.get_year()) +
            (next_date.get_month() - start_date.get_month())
        )
        next_date.subtract_months(n_months % mult)

        # dim
        days_in_month = datetimeutils.get_days_in_month(
            next_date.get_year(), next_date.get_month())

        # Handle adjustment for 3 ways.
        if (period == RecurrencePeriod.END_OF_MONTH.value or
                next_date.get_day() >= days_in_month):
            # Set to last day of the month.
            next_date.set_day(days_in_month)
        else:
            # Same day as the start.
            next_date.set_day(start_date.get_day())

        # Adjust for dates on the weekend.
        if (period == RecurrencePeriod.YEAR.value or period == RecurrencePeriod.MONTH.value or
                period == RecurrencePeriod.END_OF_MONTH.value):
            weekday = next_date.get_day_name()
            if weekday == "Saturday" or weekday == "Sunday":
                if wadj == WeekendAdjustment.BACK.value:
                    next_date.subtract_days(1 if weekday == "Saturday" else 2)
                elif wadj == WeekendAdjustment.FORWARD.value:
                    next_date.add_days(2 if weekday == "Saturday" else 1)

    return next_date.value.date()
665503
def handle_get_txn_req(self, request: Request, frm: str):
        
        ledger_id = request.operation.get(f.LEDGER_ID.nm, DOMAIN_LEDGER_ID)
        if ledger_id not in self.ledger_to_req_handler:
            self.send_nack_to_client((request.identifier, request.reqId),
                                     'Invalid ledger id {}'.format(ledger_id),
                                     frm)
            return

        seq_no = request.operation.get(DATA)
        self.send_ack_to_client((request.identifier, request.reqId), frm)
        ledger = self.getLedger(ledger_id)

        try:
            txn = self.getReplyFromLedger(ledger, seq_no)
        except KeyError:
            txn = None

        if txn is None:
            logger.debug(
                "{} can not handle GET_TXN request: ledger doesn't "
                "have txn with seqNo={}".format(self, str(seq_no)))

        result = {
            f.IDENTIFIER.nm: request.identifier,
            f.REQ_ID.nm: request.reqId,
            TXN_TYPE: request.operation[TXN_TYPE],
            DATA: None
        }

        if txn:
            result[DATA] = txn.result
            result[f.SEQ_NO.nm] = get_seq_no(txn.result)

        self.transmitToClient(Reply(result), frm)
689930
def txn2epoch(self, txn: dict) -> int:
        

        rv = None
        if self == Protocol.V_13:
            rv = txn['result']['txnTime']
        else:
            rv = txn['result']['txnMetadata']['txnTime']

        return rv
727165
def getrawtransaction(self, txid: str, decrypt: int=0) -> dict:
        ''''''

        q = 'getrawtransaction?txid={txid}&decrypt={decrypt}'.format(txid=txid, decrypt=decrypt)

        return cast(dict, self.api_fetch(q))
463685
def deliver_tx(self, raw_transaction):
        

        self.abort_if_abci_chain_is_not_synced()

        logger.debug('deliver_tx: %s', raw_transaction)
        transaction = self.bigchaindb.is_valid_transaction(
            decode_transaction(raw_transaction), self.block_transactions)

        if not transaction:
            logger.debug('deliver_tx: INVALID')
            return ResponseDeliverTx(code=CodeTypeError)
        else:
            logger.debug('storing tx')
            self.block_txn_ids.append(transaction.id)
            self.block_transactions.append(transaction)
            return ResponseDeliverTx(code=CodeTypeOk)
1015538
async def log_transaction(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		coinid = params.get("coinid")

		if not coinid in ["QTUM", "PUT"]:
			return {"error":400, "reason": "Missed or invalid coinid"}

		database = client[settings.TXS]
		source_collection = database[coinid]

		await source_collection.find_one_and_update({"txid":params.get("txid")},{"$set":{
				"blocknumber":params.get("blocknumber"),
				"blockhash":params.get("blockhash"),
				"gasLimit":params.get("gasLimit"),
				"gasPrice":params.get("gasPrice"),
			}})
		return {"success":True}