https://developers.coinbase.com/api/v2#show-a-transaction
169694
def get_transaction(self, account_id, transaction_id, **params):
        """"""
        response = self._get(
            'v2', 'accounts', account_id, 'transactions', transaction_id, params=params)
        return self._make_api_object(response, Transaction)
574264
def ddl_transaction(&block)
        if Base.connection.supports_ddl_transactions?
          Base.transaction { block.call }
        else
          block.call
        end
      end
504223
def pushtx(tx_hex, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert is_valid_coin_symbol(coin_symbol)
    assert api_key, 'api_key required'

    url = _get_pushtx_url(coin_symbol=coin_symbol)

    logger.info(url)

    data = {'tx': tx_hex}

    params = {'token': api_key}

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
681579
function ManagePendingTransactionStatus($txnID, $action) {
    if (!in_array($action, array('Accept', 'Deny'))) return FALSE;
    $values['TRANSACTIONID'] = $txnID;
    $values['ACTION'] = $action;
    return $this->_request($values, 'ManagePendingTransactionStatus');
  }
49254
def commit_deposit(self, account_id, deposit_id, **params):
        """"""
        response = self._post(
            'v2', 'accounts', account_id, 'deposits', deposit_id, 'commit',
            data=params)
        return self._make_api_object(response, Deposit)
499794
def listtransactions(self, account="", many=999, since=0):
        """"""
        return self.req("listtransactions", [account, many, since])
479324
def create_transaction(self):
        """"""
        request = urlllib.request.urlopen(
            urllib.parse.urljoin(self.base_url, 'fcr:tx'))
        self.transaction = request.read()
1368899
function Transaction (network = networks.bitcoin) {
  this.version = 1
  this.locktime = 0
  this.ins = []
  this.outs = []
  this.network = network
  if (coins.isZcash(network)) {
    // ZCash version >= 2
    this.joinsplits = []
    this.joinsplitPubkey = []
    this.joinsplitSig = []
    // ZCash version >= 3
    this.overwintered = 0  // 1 if the transaction is post overwinter upgrade, 0 otherwise
    this.versionGroupId = 0  // 0x03C48270 (63210096) for overwinter and 0x892F2085 (2301567109) for sapling
    this.expiryHeight = 0  // Block height after which this transactions will expire, or 0 to disable expiry
    // ZCash version >= 4
    this.valueBalance = 0
    this.vShieldedSpend = []
    this.vShieldedOutput = []
    this.bindingSig = 0
  }
  if (coins.isDash(network)) {
    // Dash version = 3
    this.type = 0
    this.extraPayload = Buffer.alloc(0)
  }
}
877012
function transact(transaction, api, secret, options, converter, callback) {
  if (options.submit === false) {
    prepareAndOptionallySign.apply(this, arguments);
  } else {
    prepareAndSignAndSubmit.apply(this, arguments);
  }
}
89795
function TXDBState(wid, id) {
  this.wid = wid;
  this.id = id;
  this.tx = 0;
  this.coin = 0;
  this.unconfirmed = 0;
  this.confirmed = 0;
  this.committed = false;
}
214682
def get_broadcast_transactions(coin_symbol='btc', limit=10, api_key=None):
    
    url = make_url(coin_symbol, 'txs')

    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 = get_valid_json(r)

    unconfirmed_txs = []
    for unconfirmed_tx in response_dict:
        unconfirmed_tx['received'] = parser.parse(unconfirmed_tx['received'])
        unconfirmed_txs.append(unconfirmed_tx)
    return unconfirmed_txs
730981
def processPointOfSalePayment(request):
    '''
    
    '''
    print('Request data is: %s' % request.GET)

    # iOS transactions put all response information in the data key:
    data = json.loads(request.GET.get('data','{}'))
    if data:
        status = data.get('status')
        errorCode = data.get('error_code')
        errorDescription = errorCode

        try:
            stateData = data.get('state','')
            if stateData:
                metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
            else:
                metadata = {}
        except (TypeError, ValueError, binascii.Error):
            logger.error('Invalid metadata passed from Square app.')
            messages.error(
                request,
                format_html(
                    '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                    str(_('ERROR: Error with Square point of sale transaction attempt.')),
                    str(_('Invalid metadata passed from Square app.')),
                )
            )
            return HttpResponseRedirect(reverse('showRegSummary'))

        # This is the normal transaction identifier, which will be stored in the
        # database as a SquarePaymentRecord
        serverTransId = data.get('transaction_id')

        # This is the only identifier passed for non-card transactions.
        clientTransId = data.get('client_transaction_id')
    else:
        # Android transactions use this GET response syntax
        errorCode = request.GET.get('com.squareup.pos.ERROR_CODE')
        errorDescription = request.GET.get('com.squareup.pos.ERROR_DESCRIPTION')
        status = 'ok' if not errorCode else 'error'

        # This is the normal transaction identifier, which will be stored in the
        # database as a SquarePaymentRecord
        serverTransId = request.GET.get('com.squareup.pos.SERVER_TRANSACTION_ID')

        # This is the only identifier passed for non-card transactions.
        clientTransId = request.GET.get('com.squareup.pos.CLIENT_TRANSACTION_ID')

        # Load the metadata, which includes the registration or invoice ids
        try:
            stateData = request.GET.get('com.squareup.pos.REQUEST_METADATA','')
            if stateData:
                metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
            else:
                metadata = {}

        except (TypeError, ValueError, binascii.Error):
            logger.error('Invalid metadata passed from Square app.')
            messages.error(
                request,
                format_html(
                    '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                    str(_('ERROR: Error with Square point of sale transaction attempt.')),
                    str(_('Invalid metadata passed from Square app.')),
                )
            )
            return HttpResponseRedirect(reverse('showRegSummary'))

    # Other things that can be passed in the metadata
    sourceUrl = metadata.get('sourceUrl',reverse('showRegSummary'))
    successUrl = metadata.get('successUrl',reverse('registration'))
    submissionUserId = metadata.get('userId', getattr(getattr(request,'user',None),'id',None))
    transactionType = metadata.get('transaction_type')
    taxable = metadata.get('taxable', False)
    addSessionInfo = metadata.get('addSessionInfo',False)
    customerEmail = metadata.get('customerEmail')

    if errorCode or status != 'ok':
        # Return the user to their original page with the error message displayed.
        logger.error('Error with Square point of sale transaction attempt.  CODE: %s; DESCRIPTION: %s' % (errorCode, errorDescription))
        messages.error(
            request,
            format_html(
                '<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
                str(_('ERROR: Error with Square point of sale transaction attempt.')), errorCode, errorDescription
            )
        )
        return HttpResponseRedirect(sourceUrl)

    api_instance = TransactionsApi()
    api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','')
    location_id = getattr(settings,'SQUARE_LOCATION_ID','')

    if serverTransId:
        try:
            api_response = api_instance.retrieve_transaction(transaction_id=serverTransId,location_id=location_id)
        except ApiException:
            logger.error('Unable to find Square transaction by server ID.')
            messages.error(request,_('ERROR: Unable to find Square transaction by server ID.'))
            return HttpResponseRedirect(sourceUrl)
        if api_response.errors:
            logger.error('Unable to find Square transaction by server ID: %s' % api_response.errors)
            messages.error(request,str(_('ERROR: Unable to find Square transaction by server ID:')) + api_response.errors)
            return HttpResponseRedirect(sourceUrl)
        transaction = api_response.transaction
    elif clientTransId:
        # Try to find the transaction in the 50 most recent transactions
        try:
            api_response = api_instance.list_transactions(location_id=location_id)
        except ApiException:
            logger.error('Unable to find Square transaction by client ID.')
            messages.error(request,_('ERROR: Unable to find Square transaction by client ID.'))
            return HttpResponseRedirect(sourceUrl)
        if api_response.errors:
            logger.error('Unable to find Square transaction by client ID: %s' % api_response.errors)
            messages.error(request,str(_('ERROR: Unable to find Square transaction by client ID:')) + api_response.errors)
            return HttpResponseRedirect(sourceUrl)
        transactions_list = [x for x in api_response.transactions if x.client_id == clientTransId]
        if len(transactions_list) == 1:
            transaction = transactions_list[0]
        else:
            logger.error('Returned client transaction ID not found.')
            messages.error(request,_('ERROR: Returned client transaction ID not found.'))
            return HttpResponseRedirect(sourceUrl)
    else:
        logger.error('An unknown error has occurred with Square point of sale transaction attempt.')
        messages.error(request,_('ERROR: An unknown error has occurred with Square point of sale transaction attempt.'))
        return HttpResponseRedirect(sourceUrl)

    # Get total information from the transaction for handling invoice.
    this_total = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \
        sum([x.amount_money.amount / 100 for x in transaction.refunds or []])

    # Parse if a specific submission user is indicated
    submissionUser = None
    if submissionUserId:
        try:
            submissionUser = User.objects.get(id=int(submissionUserId))
        except (ValueError, ObjectDoesNotExist):
            logger.warning('Invalid user passed, submissionUser will not be recorded.')

    if 'registration' in metadata.keys():
        try:
            tr_id = int(metadata.get('registration'))
            tr = TemporaryRegistration.objects.get(id=tr_id)
        except (ValueError, TypeError, ObjectDoesNotExist):
            logger.error('Invalid registration ID passed: %s' % metadata.get('registration'))
            messages.error(
                request,
                str(_('ERROR: Invalid registration ID passed')) + ': %s' % metadata.get('registration')
            )
            return HttpResponseRedirect(sourceUrl)

        tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes'))
        tr.save()
        this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser)
        this_description = _('Registration Payment: #%s' % tr_id)

    elif 'invoice' in metadata.keys():
        try:
            this_invoice = Invoice.objects.get(id=int(metadata.get('invoice')))
            this_description = _('Invoice Payment: %s' % this_invoice.id)

        except (ValueError, TypeError, ObjectDoesNotExist):
            logger.error('Invalid invoice ID passed: %s' % metadata.get('invoice'))
            messages.error(
                request,
                str(_('ERROR: Invalid invoice ID passed')) + ': %s' % metadata.get('invoice')
            )
            return HttpResponseRedirect(sourceUrl)
    else:
        # Gift certificates automatically get a nicer invoice description
        if transactionType == 'Gift Certificate':
            this_description = _('Gift Certificate Purchase')
        else:
            this_description = transactionType
        this_invoice = Invoice.create_from_item(
            this_total,
            this_description,
            submissionUser=submissionUser,
            calculate_taxes=(taxable is not False),
            transactionType=transactionType,
        )

    paymentRecord, created = SquarePaymentRecord.objects.get_or_create(
        transactionId=transaction.id,
        locationId=transaction.location_id,
        defaults={'invoice': this_invoice,}
    )
    if created:
        # We process the payment now, and enqueue the job to retrieve the
        # transaction again once fees have been calculated by Square
        this_invoice.processPayment(
            amount=this_total,
            fees=0,
            paidOnline=True,
            methodName='Square Point of Sale',
            methodTxn=transaction.id,
            notify=customerEmail,
        )
    updateSquareFees.schedule(args=(paymentRecord,), delay=60)

    if addSessionInfo:
        paymentSession = request.session.get(INVOICE_VALIDATION_STR, {})

        paymentSession.update({
            'invoiceID': str(this_invoice.id),
            'amount': this_total,
            'successUrl': successUrl,
        })
        request.session[INVOICE_VALIDATION_STR] = paymentSession

    return HttpResponseRedirect(successUrl)
125495
@VisibleForTesting
    void addCoinbaseTransaction(byte[] pubKeyTo, Coin value, final int height) {
        unCacheTransactions();
        transactions = new ArrayList<>();
        Transaction coinbase = new Transaction(params);
        final ScriptBuilder inputBuilder = new ScriptBuilder();

        if (height >= Block.BLOCK_HEIGHT_GENESIS) {
            inputBuilder.number(height);
        }
        inputBuilder.data(new byte[]{(byte) txCounter, (byte) (txCounter++ >> 8)});

        // A real coinbase transaction has some stuff in the scriptSig like the extraNonce and difficulty. The
        // transactions are distinguished by every TX output going to a different key.
        //
        // Here we will do things a bit differently so a new address isn't needed every time. We'll put a simple
        // counter in the scriptSig so every transaction has a different hash.
        coinbase.addInput(new TransactionInput(params, coinbase,
                inputBuilder.build().getProgram()));
        coinbase.addOutput(new TransactionOutput(params, coinbase, value,
                ScriptBuilder.createP2PKOutputScript(ECKey.fromPublicOnly(pubKeyTo)).getProgram()));
        transactions.add(coinbase);
        coinbase.setParent(this);
        coinbase.length = coinbase.unsafeBitcoinSerialize().length;
        adjustLength(transactions.size(), coinbase.length);
    }
794013
def transaction_error_code(self):
        """"""
        error = self.response_doc.find('transaction_error')
        if error is not None:
            code = error.find('error_code')
            if code is not None:
                return code.text
949830
def witness_commitment
      return nil unless coinbase_tx?
      outputs.each do |output|
        commitment = output.script_pubkey.witness_commitment
        return commitment if commitment
      end
      nil
    end
878518
async def post(self, public_key=None):
		
		if settings.SIGNATURE_VERIFICATION:
			super().verify()

		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 = message.get("cid")
		read_price = message.get("price")
		coinid = message.get("coinid")
		buyer_access_string = message.get("buyer_access_string")
	
		if not all([buyer_access_string, coinid, str(cid).isdigit()]):
			self.set_status(400)
			self.write({"error":400, "reason":"Missed required fields"})
			raise tornado.web.Finish

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

		# Get cid price from bridge
		if not read_price:
			read_price = await self.account.blockchain.getreadprice(cid=cid)

		buyer_address = self.account.validator[coinid](public_key)
		owneraddr = await self.account.blockchain.ownerbycid(cid=cid)

		# Check if public key exists
		account = await self.account.getaccountdata(public_key=public_key)
		if "error" in account.keys():
			# If account does not exist
			self.set_status(account["error"])
			self.write(account)
			raise tornado.web.Finish

		#Get sellers balance
		balances = await self.account.balance.get_wallets(coinid=coinid, uid=account["id"])

		# Check if current content does not belong to current user
		if owneraddr == buyer_address:
			self.set_status(400)
			self.write({"error":400, 
						"reason":"Content belongs to current user"})
			raise tornado.web.Finish

		# Get difference with balance and price
		for w in balances["wallets"]:
			if "PUT" in w.values() or "PUTTEST" in w.values():
				balance = w

		difference = int(balance["amount_active"]) - int(read_price)
		if difference < 0:
			# If Insufficient funds
			self.set_status(402)
			self.write({"error":402, "reason":"Balance is not enough"})
			raise tornado.web.Finish

		# Send request to bridge
		offer_data = {
			"cid":cid,
			"read_price":read_price,
			"offer_type":0,
			"buyer_address": buyer_address,
			"buyer_access_string":buyer_access_string
		}
		response = await self.account.blockchain.makeoffer(**offer_data)
		try:
			response["error"]
		except:
			pass
		else:
			self.set_status(response["error"])
			self.write(response)
			raise tornado.web.Finish

		await self.account.insertoffer(cid=cid, txid=response["result"]["txid"], 
											coinid=coinid, public_key=public_key)
		# Send e-mail to seller
		seller = await self.account.getaccountbywallet(wallet=owneraddr)
		if "error" in seller.keys():
			self.set_status(seller["error"])
			self.write(seller)
			raise tornado.web.Finish

		if seller.get("email"):
			emaildata = {
				"to": seller["email"],
				"subject": "Robin8 support",
     			"optional": "You`ve got an offer for content %s." % cid
			}
			await self.account.mailer.sendmail(**emaildata)


		# Freeze price at balance
		coinid = "PUT"
		await self.account.balance.freeze(uid=account["id"],coinid=coinid, 
																amount=read_price)

		# Set fee
		fee = await billing.set_make_offer_fee(buyer_address=buyer_address)
		if "error" in fee.keys():
			self.set_status(fee["error"])
			self.write(fee)
			raise tornado.web.Finish

		response["offer_type"] = "read_access"
		del response["result"]		

		self.write(response)
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