Return a list of grpc requests.

        Returns list from an input list of etcd3.transactions.{Put, Get,
        Delete, Txn} objects.
7065
def _ops_to_requests(self, ops):
        
        request_ops = []
        for op in ops:
            if isinstance(op, transactions.Put):
                request = self._build_put_request(op.key, op.value,
                                                  op.lease, op.prev_kv)
                request_op = etcdrpc.RequestOp(request_put=request)
                request_ops.append(request_op)

            elif isinstance(op, transactions.Get):
                request = self._build_get_range_request(op.key, op.range_end)
                request_op = etcdrpc.RequestOp(request_range=request)
                request_ops.append(request_op)

            elif isinstance(op, transactions.Delete):
                request = self._build_delete_request(op.key, op.range_end,
                                                     op.prev_kv)
                request_op = etcdrpc.RequestOp(request_delete_range=request)
                request_ops.append(request_op)

            elif isinstance(op, transactions.Txn):
                compare = [c.build_message() for c in op.compare]
                success_ops = self._ops_to_requests(op.success)
                failure_ops = self._ops_to_requests(op.failure)
                request = etcdrpc.TxnRequest(compare=compare,
                                             success=success_ops,
                                             failure=failure_ops)
                request_op = etcdrpc.RequestOp(request_txn=request)
                request_ops.append(request_op)

            else:
                raise Exception(
                    'Unknown request class {}'.format(op.__class__))
        return request_ops
1109721
def buildTransaction(self, transaction=None):
        

        if transaction is None:
            built_transaction = {}
        else:
            built_transaction = dict(**transaction)
            self.check_forbidden_keys_in_transaction(built_transaction,
                                                     ["data", "to"])

        if self.web3.eth.defaultAccount is not empty:
            built_transaction.setdefault('from', self.web3.eth.defaultAccount)

        built_transaction['data'] = self.data_in_transaction
        built_transaction['to'] = b''
        return fill_transaction_defaults(self.web3, built_transaction)
469261
def fetch_deposits(self, limit: int) -> List[Deposit]:
        """"""
        return self._transactions(self._deposits, 'deposits', limit)
145305
def requests(self):
        ''''''
        path = pathjoin(self.path, self.name, Request.path)
        response = self.service.send(SRequest('GET', path))
        # a bin behaves as a push-down store --- better to return the requests
        # in order of appearance
        return list(reversed(Request.from_response(response, bin=self)))
4785
public Collection<KeyTransaction> list(List<String> queryParams)
    {
        return HTTP.GET("/v2/key_transactions.json", null, queryParams, KEY_TRANSACTIONS).get();
    }
256417
def get_transactions(self, account_id, **params):
        """"""
        response = self._get('v2', 'accounts', account_id, 'transactions', params=params)
        return self._make_api_object(response, Transaction)
211829
def fetch_sender_txs(self):
        
        
        # fetch remaining sender transactions
        if len(self.sender_info.keys()) > 0:

            sender_txids = self.sender_info.keys()[:]
            sender_txid_batches = []
            batch_size = 20

            for i in xrange(0, len(sender_txids), batch_size ):
                sender_txid_batches.append( sender_txids[i:i+batch_size] )

            for i in xrange(0, len(sender_txid_batches)):

                sender_txid_batch = sender_txid_batches[i]
                log.debug("Fetch %s TXs via JSON-RPC (%s-%s of %s)" % (len(sender_txid_batch), i * batch_size, i * batch_size + len(sender_txid_batch), len(sender_txids)))

                sender_txs = None

                for j in xrange(0, 5):
                    sender_txs = self.fetch_txs_rpc( self.bitcoind_opts, sender_txid_batch )
                    if sender_txs is None:
                        log.error("Failed to fetch transactions; trying again (%s of %s)" % (j+1, 5))
                        time.sleep(j+1)
                        continue

                    break

                if sender_txs is None:
                    raise Exception("Failed to fetch transactions")
                
                # pair back up with nulldata transactions
                for sender_txid, sender_tx in sender_txs.items():

                    assert sender_txid in self.sender_info.keys(), "Unsolicited sender tx %s" % sender_txid

                    # match sender outputs to the nulldata tx's inputs
                    for nulldata_input_vout_index in self.sender_info[sender_txid].keys():
                        if sender_txid != "0000000000000000000000000000000000000000000000000000000000000000":
                            
                            # regular tx, not coinbase 
                            assert nulldata_input_vout_index < len(sender_tx['outs']), 'Output index {} is out of bounds for {}'.format(nulldata_input_vout_index, sender_txid)

                            # save sender info 
                            self.add_sender_info(sender_txid, nulldata_input_vout_index, sender_tx['outs'][nulldata_input_vout_index])
                        
                        else:

                            # coinbase
                            self.add_sender_info(sender_txid, nulldata_input_vout_index, sender_tx['outs'][0])

                    # update accounting
                    self.num_txs_received += 1

        return True
1364077
def get_resource(self, transaction):
        
        method = getattr(transaction.resource, 'render_GET', None)

        transaction.resource.actual_content_type = None
        # Accept
        if transaction.request.accept is not None:
            transaction.resource.actual_content_type = transaction.request.accept

        # Render_GET
        try:
            resource = method(request=transaction.request)
        except NotImplementedError:
            try:
                method = getattr(transaction.resource, "render_GET_advanced", None)
                ret = method(request=transaction.request, response=transaction.response)
                if isinstance(ret, tuple) and len(ret) == 2 and isinstance(ret[1], Response) \
                        and isinstance(ret[0], Resource):
                    # Advanced handler
                    resource, response = ret
                    transaction.resource = resource
                    transaction.response = response
                    if transaction.response.code is None:
                        transaction.response.code = defines.Codes.CONTENT.number
                    return transaction
                elif isinstance(ret, tuple) and len(ret) == 3 and isinstance(ret[1], Response) \
                        and isinstance(ret[0], Resource):
                    # Advanced handler separate
                    resource, response, callback = ret
                    ret = self._handle_separate_advanced(transaction, callback)
                    if not isinstance(ret, tuple) or \
                            not (isinstance(ret[0], Resource) and isinstance(ret[1], Response)):  # pragma: no cover
                        transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
                        return transaction
                    resource, response = ret
                    transaction.resource = resource
                    transaction.response = response
                    if transaction.response.code is None:
                        transaction.response.code = defines.Codes.CONTENT.number
                    return transaction
                else:
                    raise NotImplementedError
            except NotImplementedError:
                transaction.response.code = defines.Codes.METHOD_NOT_ALLOWED.number
                return transaction

        if isinstance(resource, Resource):
            pass
        elif isinstance(resource, tuple) and len(resource) == 2:
            resource, callback = resource
            resource = self._handle_separate(transaction, callback)
            if not isinstance(resource, Resource):  # pragma: no cover
                transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
                return transaction
        else:  # pragma: no cover
            # Handle error
            transaction.response.code = defines.Codes.INTERNAL_SERVER_ERROR.number
            return transaction.response

        if resource.etag in transaction.request.etag:
            transaction.response.code = defines.Codes.VALID.number
        else:
            transaction.response.code = defines.Codes.CONTENT.number

        try:
            transaction.response.payload = resource.payload
            if resource.actual_content_type is not None \
                    and resource.actual_content_type != defines.Content_types["text/plain"]:
                transaction.response.content_type = resource.actual_content_type
        except KeyError:
            transaction.response.code = defines.Codes.NOT_ACCEPTABLE.number
            return transaction.response

        assert(isinstance(resource, Resource))
        if resource.etag is not None:
            transaction.response.etag = resource.etag
        if resource.max_age is not None:
            transaction.response.max_age = resource.max_age

        transaction.resource = resource

        return transaction
1058103
def get_blockstack_transactions_at(block_id, proxy=None, hostport=None):
    
    assert proxy or hostport, 'Need proxy or hostport'
    if proxy is None:
        proxy = connect_hostport(hostport)

    history_schema = {
        'type': 'array',
        'items': {
            'type': 'object',
            'properties': OP_HISTORY_SCHEMA['properties'],
            'required': [
                'op',
                'opcode',
                'txid',
                'vtxindex',
            ]
        }
    }

    nameop_history_schema = {
        'type': 'object',
        'properties': {
            'nameops': history_schema,
        },
        'required': [
            'nameops',
        ],
    }

    history_count_schema = {
        'type': 'object',
        'properties': {
            'count': {
                'type': 'integer',
                'minimum': 0,
            },
        },
        'required': [
            'count',
        ],
    }
    
    count_schema = json_response_schema( history_count_schema )
    nameop_schema = json_response_schema( nameop_history_schema )

    # how many nameops?
    num_nameops = None
    try:
        num_nameops = proxy.get_num_blockstack_ops_at(block_id)
        num_nameops = json_validate(count_schema, num_nameops)
        if json_is_error(num_nameops):
            return num_nameops

    except ValidationError as e:
        if BLOCKSTACK_DEBUG:
            log.exception(e)

        resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
        return resp

    except socket.timeout:
        log.error("Connection timed out")
        resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
        return resp

    except socket.error as se:
        log.error("Connection error {}".format(se.errno))
        resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
        return resp

    except Exception as ee:
        if BLOCKSTACK_DEBUG:
            log.exception(ee)

        log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
        resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
        return resp

    num_nameops = num_nameops['count']

    # grab at most 10 of these at a time
    all_nameops = []
    page_size = 10
    while len(all_nameops) < num_nameops:
        resp = {}
        try:
            resp = proxy.get_blockstack_ops_at(block_id, len(all_nameops), page_size)
            resp = json_validate(nameop_schema, resp)
            if json_is_error(resp):
                return resp

            if len(resp['nameops']) == 0:
                return {'error': 'Got zero-length nameops reply', 'http_status': 503}

            all_nameops += resp['nameops']

        except ValidationError as e:
            if BLOCKSTACK_DEBUG:
                log.exception(e)

            resp = {'error': 'Server response did not match expected schema.  You are likely communicating with an out-of-date Blockstack node.', 'http_status': 502}
            return resp

        except socket.timeout:
            log.error("Connection timed out")
            resp = {'error': 'Connection to remote host timed out.', 'http_status': 503}
            return resp

        except socket.error as se:
            log.error("Connection error {}".format(se.errno))
            resp = {'error': 'Connection to remote host failed.', 'http_status': 502}
            return resp

        except Exception as ee:
            if BLOCKSTACK_DEBUG:
                log.exception(ee)

            log.error("Caught exception while connecting to Blockstack node: {}".format(ee))
            resp = {'error': 'Failed to contact Blockstack node.  Try again with `--debug`.', 'http_status': 500}
            return resp

    return all_nameops
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
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)
274048
private List checkTransactionParticipationAndWaitForOtherTransactions(List list, MithraTransaction tx)
    {
        if (list == null) return null;
        List result = list;
        if (this.getTxParticipationMode(tx).mustParticipateInTxOnRead())
        {
            for(int i=0;i<list.size();i++)
            {
                MithraTransactionalObject mto = (MithraTransactionalObject) list.get(i);
                if (!mto.zIsParticipatingInTransaction(tx))
                {
                    result = null;
                    mto.zWaitForExclusiveWriteTx(tx);
                }
            }
        }
        return result;
    }
920664
def get_outputs_by_public_key(self, public_key):
        """"""
        txs = list(query.get_owned_ids(self.connection, public_key))
        return [TransactionLink(tx['id'], index)
                for tx in txs
                for index, output in enumerate(tx['outputs'])
                if condition_details_has_owner(output['condition']['details'],
                                               public_key)]
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
1245340
def fetch_txs_rpc( self, bitcoind_opts, txids ):
        

        headers = {'content-type': 'application/json'}
        reqs = []
        ret = {}
        for i in xrange(0, len(txids)):
            txid = txids[i]
            if txid == "0000000000000000000000000000000000000000000000000000000000000000":
                # coinbase; we never send these
                ret[txid] = {
                    'version': 1,
                    'locktime': 0,
                    'ins': [],
                    'outs': [
                        {
                            'script': '',
                            'value': 0      # not really 0, but we don't care about coinbases anyway
                        }
                    ],
                }
                continue

            req = {'method': 'getrawtransaction', 'params': [txid, 0], 'jsonrpc': '2.0', 'id': i}
            reqs.append( req )

        proto = "http"
        if bitcoind_opts.has_key('bitcoind_use_https') and bitcoind_opts['bitcoind_use_https']:
            proto = "https"
            
        server_url = "%s://%s:%s@%s:%s" % (proto, bitcoind_opts['bitcoind_user'], bitcoind_opts['bitcoind_passwd'], bitcoind_opts['bitcoind_server'], bitcoind_opts['bitcoind_port'])
        try:
            resp = requests.post( server_url, headers=headers, data=simplejson.dumps(reqs), verify=False )
        except Exception, e:
            log.exception(e)
            log.error("Failed to fetch %s transactions" % len(txids))
            return None

        # get responses
        try:
            resp_json = resp.json()
            assert type(resp_json) in [list]
        except Exception, e:
            log.exception(e)
            log.error("Failed to parse transactions")
            return None

        try:
            for resp in resp_json:
                assert 'result' in resp, "Missing result"

                txhex = resp['result']
                assert txhex is not None, "Invalid RPC response '%s' (for %s)" % (simplejson.dumps(resp), txids[resp['id']])
               
                if bits.btc_tx_is_segwit(txhex) and not get_features('segwit'):
                    # no segwit support yet
                    log.error("FATAL: SegWit transaction detected!  Support for SegWit-formatted transactions is not yet activated")
                    log.error("Please ensure your bitcoind node has `rpcserialversion=0` set.")
                    log.error("Aborting...")
                    os.abort()

                try:

                    tx_bin = txhex.decode('hex')
                    assert tx_bin is not None

                    tx_hash_bin = hashing.bin_double_sha256(tx_bin)[::-1]
                    assert tx_hash_bin is not None

                    tx_hash = tx_hash_bin.encode('hex')
                    assert tx_hash is not None

                except Exception, e:
                    log.error("Failed to calculate txid of %s" % txhex)
                    raise

                # solicited transaction?
                assert tx_hash in txids, "Unsolicited transaction %s" % tx_hash
                
                # unique?
                if tx_hash in ret.keys():
                    continue

                # parse from hex string
                txn_serializer = TxSerializer()
                txn = txn_serializer.deserialize( StringIO( binascii.unhexlify(txhex) ) )

                ret[tx_hash] = self.parse_tx( txn, {}, "", -1 )


        except Exception, e:
            log.exception(e)
            log.error("Failed to receive transactions")
            return None

        return ret
323785
async def get_txn(self, seq_no: int) -> str:
        

        LOGGER.debug('BaseAnchor.get_txn >>> seq_no: %s', seq_no)

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

        rv_json = self.pool.protocol.txn2data(resp)

        LOGGER.debug('BaseAnchor.get_txn <<< %s', rv_json)
        return rv_json
391120
def get_lists(client):
    '''  '''
    response = client.authenticated_request(client.api.Endpoints.LISTS)
    return response.json()