INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return a > b.
def uint16_gt(a: int, b: int) -> bool: """ Return a > b. """ half_mod = 0x8000 return (((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)))
Return a >= b.
def uint16_gte(a: int, b: int) -> bool: """ Return a >= b. """ return (a == b) or uint16_gt(a, b)
Return a > b.
def uint32_gt(a: int, b: int) -> bool: """ Return a > b. """ half_mod = 0x80000000 return (((a < b) and ((b - a) > half_mod)) or ((a > b) and ((a - b) < half_mod)))
Return a >= b.
def uint32_gte(a: int, b: int) -> bool: """ Return a >= b. """ return (a == b) or uint32_gt(a, b)
Bring up interface. Equivalent to ifconfig [iface] up.
def up(self): ''' Bring up interface. Equivalent to ifconfig [iface] up. ''' # Set new flags flags = self.ifflags | IFF_UP self.ifflags = flags self.get_mtu()
Open file corresponding to the TUN device.
def open(self): ''' Open file corresponding to the TUN device. ''' self.fd = open('/dev/net/tun', 'rb+', buffering=0) tun_flags = IFF_TAP | IFF_NO_PI | IFF_PERSIST ifr = struct.pack('16sH', self.name, tun_flags) fcntl.ioctl(self.fd, TUNSETIFF, ifr) fcntl.ioctl(self.fd, TU...
Gather ICE candidates.
async def gather(self): """ Gather ICE candidates. """ if self.__state == 'new': self.__setState('gathering') await self._connection.gather_candidates() self.__setState('completed')
Retrieve the ICE parameters of the ICE gatherer. :rtype: RTCIceParameters
def getLocalParameters(self): """ Retrieve the ICE parameters of the ICE gatherer. :rtype: RTCIceParameters """ return RTCIceParameters( usernameFragment=self._connection.local_username, password=self._connection.local_password)
Add a remote candidate.
def addRemoteCandidate(self, candidate): """ Add a remote candidate. """ # FIXME: don't use private member! if not self._connection._remote_candidates_end: if candidate is None: self._connection.add_remote_candidate(None) else: ...
Initiate connectivity checks. :param: remoteParameters: The :class:`RTCIceParameters` associated with the remote :class:`RTCIceTransport`.
async def start(self, remoteParameters): """ Initiate connectivity checks. :param: remoteParameters: The :class:`RTCIceParameters` associated with the remote :class:`RTCIceTransport`. """ if self.state == 'closed': raise InvalidState...
Send `data` across the data channel to the remote peer.
def send(self, data): """ Send `data` across the data channel to the remote peer. """ if self.readyState != 'open': raise InvalidStateError if not isinstance(data, (str, bytes)): raise ValueError('Cannot send unsupported data type: %s' % type(data)) ...
Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param: codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order of preference. If empty, restores the defa...
def setCodecPreferences(self, codecs): """ Override the default codec preferences. See :meth:`RTCRtpSender.getCapabilities` and :meth:`RTCRtpReceiver.getCapabilities` for the supported codecs. :param: codecs: A list of :class:`RTCRtpCodecCapability`, in decreasing order ...
Permanently stops the :class:`RTCRtpTransceiver`.
async def stop(self): """ Permanently stops the :class:`RTCRtpTransceiver`. """ await self.__receiver.stop() await self.__sender.stop() self.__stopped = True
Start discarding media.
async def start(self): """ Start discarding media. """ for track, task in self.__tracks.items(): if task is None: self.__tracks[track] = asyncio.ensure_future(blackhole_consume(track))
Stop discarding media.
async def stop(self): """ Stop discarding media. """ for task in self.__tracks.values(): if task is not None: task.cancel() self.__tracks = {}
Add a track to be recorded. :param: track: An :class:`aiortc.AudioStreamTrack` or :class:`aiortc.VideoStreamTrack`.
def addTrack(self, track): """ Add a track to be recorded. :param: track: An :class:`aiortc.AudioStreamTrack` or :class:`aiortc.VideoStreamTrack`. """ if track.kind == 'audio': if self.__container.format.name == 'wav': codec_name = 'pcm_s16le' ...
Start recording.
async def start(self): """ Start recording. """ for track, context in self.__tracks.items(): if context.task is None: context.task = asyncio.ensure_future(self.__run_track(track, context))
Stop recording.
async def stop(self): """ Stop recording. """ if self.__container: for track, context in self.__tracks.items(): if context.task is not None: context.task.cancel() context.task = None for packet in con...
The date and time after which the certificate will be considered invalid.
def expires(self): """ The date and time after which the certificate will be considered invalid. """ not_after = self._cert.get_notAfter().decode('ascii') return datetime.datetime.strptime(not_after, '%Y%m%d%H%M%SZ').replace( tzinfo=datetime.timezone.utc)
Create and return an X.509 certificate and corresponding private key. :rtype: RTCCertificate
def generateCertificate(cls): """ Create and return an X.509 certificate and corresponding private key. :rtype: RTCCertificate """ key = generate_key() cert = generate_certificate(key) return cls(key=key, cert=cert)
Start DTLS transport negotiation with the parameters of the remote DTLS transport. :param: remoteParameters: An :class:`RTCDtlsParameters`.
async def start(self, remoteParameters): """ Start DTLS transport negotiation with the parameters of the remote DTLS transport. :param: remoteParameters: An :class:`RTCDtlsParameters`. """ assert self._state == State.NEW assert len(remoteParameters.fingerprints) ...
Stop and close the DTLS transport.
async def stop(self): """ Stop and close the DTLS transport. """ if self._task is not None: self._task.cancel() self._task = None if self._state in [State.CONNECTING, State.CONNECTED]: lib.SSL_shutdown(self.ssl) try: ...
Flush outgoing data which OpenSSL put in our BIO to the transport.
async def _write_ssl(self): """ Flush outgoing data which OpenSSL put in our BIO to the transport. """ pending = lib.BIO_ctrl_pending(self.write_bio) if pending > 0: result = lib.BIO_read(self.write_bio, self.write_cdata, len(self.write_cdata)) await self....
For testing purposes.
def set_estimate(self, bitrate: int, now_ms: int): """ For testing purposes. """ self.current_bitrate = self._clamp_bitrate(bitrate, bitrate) self.current_bitrate_initialized = True self.last_change_ms = now_ms
Receive the next :class:`~av.audio.frame.AudioFrame`. The base implementation just reads silence, subclass :class:`AudioStreamTrack` to provide a useful implementation.
async def recv(self): """ Receive the next :class:`~av.audio.frame.AudioFrame`. The base implementation just reads silence, subclass :class:`AudioStreamTrack` to provide a useful implementation. """ if self.readyState != 'live': raise MediaStreamError ...
Receive the next :class:`~av.video.frame.VideoFrame`. The base implementation just reads a 640x480 green frame at 30fps, subclass :class:`VideoStreamTrack` to provide a useful implementation.
async def recv(self): """ Receive the next :class:`~av.video.frame.VideoFrame`. The base implementation just reads a 640x480 green frame at 30fps, subclass :class:`VideoStreamTrack` to provide a useful implementation. """ pts, time_base = await self.next_timestamp() ...
Prune chunks up to the given TSN.
def prune_chunks(self, tsn): """ Prune chunks up to the given TSN. """ pos = -1 size = 0 for i, chunk in enumerate(self.reassembly): if uint32_gte(tsn, chunk.tsn): pos = i size += len(chunk.user_data) else: ...
Start the transport.
async def start(self, remoteCaps, remotePort): """ Start the transport. """ if not self.__started: self.__started = True self.__state = 'connecting' self._remote_port = remotePort # configure logging if logger.isEnabledFor(logg...
Stop the transport.
async def stop(self): """ Stop the transport. """ if self._association_state != self.State.CLOSED: await self._abort() self.__transport._unregister_data_receiver(self) self._set_state(self.State.CLOSED)
Initialize the association.
async def _init(self): """ Initialize the association. """ chunk = InitChunk() chunk.initiate_tag = self._local_verification_tag chunk.advertised_rwnd = self._advertised_rwnd chunk.outbound_streams = self._outbound_streams_count chunk.inbound_streams = sel...
Gets what extensions are supported by the remote party.
def _get_extensions(self, params): """ Gets what extensions are supported by the remote party. """ for k, v in params: if k == SCTP_PRSCTP_SUPPORTED: self._remote_partial_reliability = True elif k == SCTP_SUPPORTED_CHUNK_EXT: self._...
Sets what extensions are supported by the local party.
def _set_extensions(self, params): """ Sets what extensions are supported by the local party. """ extensions = [] if self._local_partial_reliability: params.append((SCTP_PRSCTP_SUPPORTED, b'')) extensions.append(ForwardTsnChunk.type) extensions.ap...
Get or create the inbound stream with the specified ID.
def _get_inbound_stream(self, stream_id): """ Get or create the inbound stream with the specified ID. """ if stream_id not in self._inbound_streams: self._inbound_streams[stream_id] = InboundStream() return self._inbound_streams[stream_id]
Handle data received from the network.
async def _handle_data(self, data): """ Handle data received from the network. """ try: _, _, verification_tag, chunks = parse_packet(data) except ValueError: return # is this an init? init_chunk = len([x for x in chunks if isinstance(x, I...
Determine if a chunk needs to be marked as abandoned. If it does, it marks the chunk and any other chunk belong to the same message as abandoned.
def _maybe_abandon(self, chunk): """ Determine if a chunk needs to be marked as abandoned. If it does, it marks the chunk and any other chunk belong to the same message as abandoned. """ if chunk._abandoned: return True abandon = ( (chunk...
Mark an incoming data TSN as received.
def _mark_received(self, tsn): """ Mark an incoming data TSN as received. """ # it's a duplicate if uint32_gte(self._last_received_tsn, tsn) or tsn in self._sack_misordered: self._sack_duplicates.append(tsn) return True # consolidate misordered en...
Receive data stream -> ULP.
async def _receive(self, stream_id, pp_id, data): """ Receive data stream -> ULP. """ await self._data_channel_receive(stream_id, pp_id, data)
Handle an incoming chunk.
async def _receive_chunk(self, chunk): """ Handle an incoming chunk. """ self.__log_debug('< %s', chunk) # common if isinstance(chunk, DataChunk): await self._receive_data_chunk(chunk) elif isinstance(chunk, SackChunk): await self._receive...
Handle a DATA chunk.
async def _receive_data_chunk(self, chunk): """ Handle a DATA chunk. """ self._sack_needed = True # mark as received if self._mark_received(chunk.tsn): return # find stream inbound_stream = self._get_inbound_stream(chunk.stream_id) #...
Handle a FORWARD TSN chunk.
async def _receive_forward_tsn_chunk(self, chunk): """ Handle a FORWARD TSN chunk. """ self._sack_needed = True # it's a duplicate if uint32_gte(self._last_received_tsn, chunk.cumulative_tsn): return def is_obsolete(x): return uint32_gt(x...
Handle a SACK chunk.
async def _receive_sack_chunk(self, chunk): """ Handle a SACK chunk. """ if uint32_gt(self._last_sacked_tsn, chunk.cumulative_tsn): return received_time = time.time() self._last_sacked_tsn = chunk.cumulative_tsn cwnd_fully_utilized = (self._flight_siz...
Handle a RE-CONFIG parameter.
async def _receive_reconfig_param(self, param): """ Handle a RE-CONFIG parameter. """ self.__log_debug('<< %s', param) if isinstance(param, StreamResetOutgoingParam): # mark closed inbound streams for stream_id in param.streams: self._inbo...
Send data ULP -> stream.
async def _send(self, stream_id, pp_id, user_data, expiry=None, max_retransmits=None, ordered=True): """ Send data ULP -> stream. """ if ordered: stream_seq = self._outbound_stream_seq.get(stream_id, 0) else: stream_seq = 0 fra...
Transmit a chunk (no bundling for now).
async def _send_chunk(self, chunk): """ Transmit a chunk (no bundling for now). """ self.__log_debug('> %s', chunk) await self.__transport._send_data(serialize_packet( self._local_port, self._remote_port, self._remote_verification_tag, ...
Build and send a selective acknowledgement (SACK) chunk.
async def _send_sack(self): """ Build and send a selective acknowledgement (SACK) chunk. """ gaps = [] gap_next = None for tsn in sorted(self._sack_misordered): pos = (tsn - self._last_received_tsn) % SCTP_TSN_MODULO if tsn == gap_next: ...
Transition the SCTP association to a new state.
def _set_state(self, state): """ Transition the SCTP association to a new state. """ if state != self._association_state: self.__log_debug('- %s -> %s', self._association_state, state) self._association_state = state if state == self.State.ESTABLISHED: ...
Transmit outbound data.
async def _transmit(self): """ Transmit outbound data. """ # send FORWARD TSN if self._forward_tsn_chunk is not None: await self._send_chunk(self._forward_tsn_chunk) self._forward_tsn_chunk = None # ensure T3 is running if not self...
Try to advance "Advanced.Peer.Ack.Point" according to RFC 3758.
def _update_advanced_peer_ack_point(self): """ Try to advance "Advanced.Peer.Ack.Point" according to RFC 3758. """ if uint32_gt(self._last_sacked_tsn, self._advanced_peer_ack_tsn): self._advanced_peer_ack_tsn = self._last_sacked_tsn done = 0 streams = {} ...
Update RTO given a new roundtrip measurement R.
def _update_rto(self, R): """ Update RTO given a new roundtrip measurement R. """ if self._srtt is None: self._rttvar = R / 2 self._srtt = R else: self._rttvar = (1 - SCTP_RTO_BETA) * self._rttvar + SCTP_RTO_BETA * abs(self._srtt - R) ...
Try to flush buffered data to the SCTP layer. We wait until the association is established, as we need to know whether we are a client or a server to correctly assign an odd/even ID to the data channels.
async def _data_channel_flush(self): """ Try to flush buffered data to the SCTP layer. We wait until the association is established, as we need to know whether we are a client or a server to correctly assign an odd/even ID to the data channels. """ if self._assoc...
Request closing the datachannel by sending an Outgoing Stream Reset Request.
def _data_channel_close(self, channel, transmit=True): """ Request closing the datachannel by sending an Outgoing Stream Reset Request. """ if channel.readyState not in ['closing', 'closed']: channel._setReadyState('closing') self._reconfig_queue.append(channel.id...
Add signaling method arguments to an argparse.ArgumentParser.
def add_signaling_arguments(parser): """ Add signaling method arguments to an argparse.ArgumentParser. """ parser.add_argument('--signaling', '-s', choices=[ 'copy-and-paste', 'tcp-socket', 'unix-socket']) parser.add_argument('--signaling-host', default='127.0.0.1', h...
Create a signaling method based on command-line arguments.
def create_signaling(args): """ Create a signaling method based on command-line arguments. """ if args.signaling == 'tcp-socket': return TcpSocketSignaling(args.signaling_host, args.signaling_port) elif args.signaling == 'unix-socket': return UnixSocketSignaling(args.signaling_path) ...
Receive the next frame.
async def recv(self): """ Receive the next frame. """ if self.readyState != 'live': raise MediaStreamError frame = await self._queue.get() if frame is None: self.stop() raise MediaStreamError return frame
Returns statistics about the RTP receiver. :rtype: :class:`RTCStatsReport`
async def getStats(self): """ Returns statistics about the RTP receiver. :rtype: :class:`RTCStatsReport` """ for ssrc, stream in self.__remote_streams.items(): self.__stats.add(RTCInboundRtpStreamStats( # RTCStats timestamp=clock.curre...
Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds.
def getSynchronizationSources(self): """ Returns a :class:`RTCRtpSynchronizationSource` for each unique SSRC identifier received in the last 10 seconds. """ cutoff = clock.current_datetime() - datetime.timedelta(seconds=10) sources = [] for source, timestamp in se...
Attempt to set the parameters controlling the receiving of media. :param: parameters: The :class:`RTCRtpParameters` for the receiver.
async def receive(self, parameters: RTCRtpReceiveParameters): """ Attempt to set the parameters controlling the receiving of media. :param: parameters: The :class:`RTCRtpParameters` for the receiver. """ if not self.__started: for codec in parameters.codecs: ...
Irreversibly stop the receiver.
async def stop(self): """ Irreversibly stop the receiver. """ if self.__started: self.__transport._unregister_rtp_receiver(self) self.__stop_decoder() self.__rtcp_task.cancel() await self.__rtcp_exited.wait()
Handle an incoming RTP packet.
async def _handle_rtp_packet(self, packet: RtpPacket, arrival_time_ms: int): """ Handle an incoming RTP packet. """ self.__log_debug('< %s', packet) # feed bitrate estimator if self.__remote_bitrate_estimator is not None: if packet.extensions.abs_send_time is...
Send an RTCP packet to report missing RTP packets.
async def _send_rtcp_nack(self, media_ssrc, lost): """ Send an RTCP packet to report missing RTP packets. """ if self.__rtcp_ssrc is not None: packet = RtcpRtpfbPacket( fmt=RTCP_RTPFB_NACK, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc) packet.lost ...
Send an RTCP packet to report picture loss.
async def _send_rtcp_pli(self, media_ssrc): """ Send an RTCP packet to report picture loss. """ if self.__rtcp_ssrc is not None: packet = RtcpPsfbPacket(fmt=RTCP_PSFB_PLI, ssrc=self.__rtcp_ssrc, media_ssrc=media_ssrc) await self._send_rtcp(packet)
Stop the decoder thread, which will in turn stop the track.
def __stop_decoder(self): """ Stop the decoder thread, which will in turn stop the track. """ if self.__decoder_thread: self.__decoder_queue.put(None) self.__decoder_thread.join() self.__decoder_thread = None
This is usually an implementation of Ledger
def init_domain_ledger(self): """ This is usually an implementation of Ledger """ if self.config.primaryStorage is None: genesis_txn_initiator = GenesisTxnInitiatorFromFile( self.genesis_dir, self.config.domainTransactionsFile) return Ledger( ...
All the data of the transaction might not be stored in ledger so the extra data that is omitted from ledger needs to be fetched from the appropriate data store :param txn: :return:
def update_txn_with_extra_data(self, txn): """ All the data of the transaction might not be stored in ledger so the extra data that is omitted from ledger needs to be fetched from the appropriate data store :param txn: :return: """ # For RAW and ENC attrib...
Make key(path)-value pair for state from ATTRIB or GET_ATTR :return: state path, state value, value for attribute store
def prepare_attr_for_state(txn, path_only=False): """ Make key(path)-value pair for state from ATTRIB or GET_ATTR :return: state path, state value, value for attribute store """ assert get_type(txn) == ATTRIB txn_data = get_payload_data(txn) nym = txn_data[TARGET_NYM] attr_type, attr_key...
ATTR and GET_ATTR can have one of 'raw', 'enc' and 'hash' fields. This method checks which of them presents and return it's name and value in it.
def _extract_attr_typed_value(txn_data): """ ATTR and GET_ATTR can have one of 'raw', 'enc' and 'hash' fields. This method checks which of them presents and return it's name and value in it. """ existing_keys = [key for key in ALL_ATR_KEYS if key in txn_data] if len(existing_keys) == 0: ...
Test for the directory, open old and new ledger, migrate data, rename directories
def _migrate_ledger(data_directory, old_ledger_file, new_ledger_file, serializer: MappingSerializer = None): """ Test for the directory, open old and new ledger, migrate data, rename directories """ # we should have ChunkedFileStorage implementation of the Ledger...
Get a nym, if role is provided then get nym with that role :param nym: :param role: :param isCommitted: :return:
def getNym(self, nym, role=None, isCommitted=True): """ Get a nym, if role is provided then get nym with that role :param nym: :param role: :param isCommitted: :return: """ try: seqNo, txnTime, ta, actual_role, verkey = self.get(nym, isCommitte...
Unschedule current action Note that it does not add record to action log and does not do required steps to resume previous action. If you need this - use _cancelScheduledAction
def _unscheduleAction(self): """ Unschedule current action Note that it does not add record to action log and does not do required steps to resume previous action. If you need this - use _cancelScheduledAction """ logger.trace("{} unscheduling actions".format(se...
Find rule_id for incoming action_id and return AuthConstraint instance
def get_auth_constraint(self, action_id: str) -> AbstractAuthConstraint: """ Find rule_id for incoming action_id and return AuthConstraint instance """ if self.anyone_can_write_map: return self._find_auth_constraint(action_id, self.anyone_can_write_map, from_local=True) ...
Appends event to log Be careful it opens file every time!
def _append(self, ev_type: Enum, data: ActionLogData) -> None: """ Appends event to log Be careful it opens file every time! """ event = ActionLogEvent(None, ev_type, data, types=self._event_types) with open(self._file_path, mode='a+', newline='') as f: f.writ...
The state trie stores the hash of the whole attribute data at: the did+attribute name if the data is plaintext (RAW) the did+hash(attribute) if the data is encrypted (ENC) If the attribute is HASH, then nothing is stored in attribute store, the trie stores a blank value for the k...
def update_state(self, txn, prev_result, is_committed=True) -> None: """ The state trie stores the hash of the whole attribute data at: the did+attribute name if the data is plaintext (RAW) the did+hash(attribute) if the data is encrypted (ENC) If the attribute is HASH, t...
depends on config
def create_auth_strategy(self): """depends on config""" if self.config.authPolicy == LOCAL_AUTH_POLICY: return LocalAuthStrategy(auth_map=self.auth_map, anyone_can_write_map=self.anyone_can_write_map if self.anyone_can_write else None) elif self.c...
Return path to state as 'str' type or None
def gen_txn_path(self, txn): """Return path to state as 'str' type or None""" txn_type = get_type(txn) if txn_type not in self.state_update_handlers: logger.error('Cannot generate id for txn of type {}'.format(txn_type)) return None if txn_type == NYM: ...
For getting reply we need: 1. Get REVOC_REG_ENTRY by "TO" timestamp from state 2. If FROM is given in request, then Get REVOC_REG_ENTRY by "FROM" timestamp from state 3. Get ISSUANCE_TYPE for REVOC_REG_DEF (revoked/issued strategy) 4. Compute issued and revoked indices by corresponding s...
def handleGetRevocRegDelta(self, request: Request): """ For getting reply we need: 1. Get REVOC_REG_ENTRY by "TO" timestamp from state 2. If FROM is given in request, then Get REVOC_REG_ENTRY by "FROM" timestamp from state 3. Get ISSUANCE_TYPE for REVOC_REG_DEF (revoked/issued st...
Queries state for data on specified path :param path: path to data :param isCommitted: queries the committed state root if True else the uncommitted root :param with_proof: creates proof if True :return: data
def lookup(self, path, isCommitted=True, with_proof=False) -> (str, int): """ Queries state for data on specified path :param path: path to data :param isCommitted: queries the committed state root if True else the uncommitted root :param with_proof: creates proof if True ...
The state trie stores the hash of the whole attribute data at: the did+attribute name if the data is plaintext (RAW) the did+hash(attribute) if the data is encrypted (ENC) If the attribute is HASH, then nothing is stored in attribute store, the trie stores a blank value for the k...
def _addAttr(self, txn, isCommitted=False) -> None: """ The state trie stores the hash of the whole attribute data at: the did+attribute name if the data is plaintext (RAW) the did+hash(attribute) if the data is encrypted (ENC) If the attribute is HASH, then nothing is st...
Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger
def transform_txn_for_ledger(txn): """ Some transactions need to be transformed before they can be stored in the ledger, eg. storing certain payload in another data store and only its hash in the ledger """ if get_type(txn) == ATTRIB: txn = DomainReqHandler.tr...
Creating copy of result so that `RAW`, `ENC` or `HASH` can be replaced by their hashes. We do not insert actual attribute data in the ledger but only the hash of it.
def transform_attrib_for_ledger(txn): """ Creating copy of result so that `RAW`, `ENC` or `HASH` can be replaced by their hashes. We do not insert actual attribute data in the ledger but only the hash of it. """ txn = deepcopy(txn) txn_data = get_payload_data(txn)...
Encrypt the provided value with symmetric encryption :param val: the value to encrypt :param secretKey: Optional key, if provided should be either in hex or bytes :return: Tuple of the encrypted value and secret key encoded in hex
def getSymmetricallyEncryptedVal(val, secretKey: Union[str, bytes] = None) -> \ Tuple[str, str]: """ Encrypt the provided value with symmetric encryption :param val: the value to encrypt :param secretKey: Optional key, if provided should be either in hex or bytes :return: Tuple of the encry...
Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True
def getIndex(predicateFn: Callable[[T], bool], items: List[T]) -> int: """ Finds the index of an item in list, which satisfies predicate :param predicateFn: predicate function to run on items of list :param items: list of tuples :return: first index for which predicate function returns True """ ...
Create base transactions :param key: ledger :param force: replace existing transaction files
def setupTxns(self, key, force: bool = False): """ Create base transactions :param key: ledger :param force: replace existing transaction files """ import data dataDir = os.path.dirname(data.__file__) # TODO: Need to get "test" and "live" from ENVS prope...
Check if an image with a given tag exists. No side-effects. Idempotent. Handles ImageNotFound and APIError exceptions, but only reraises APIError.
def getImageByTag(tag): '''Check if an image with a given tag exists. No side-effects. Idempotent. Handles ImageNotFound and APIError exceptions, but only reraises APIError. ''' require_str("tag", tag) image = None try: image = client.images.get(tag) print("Found image", tag, "....
Check if an image with a given tag exists. If not, build an image from using a given dockerfile in a given path, tagging it with a given tag. No extra side effects. Handles and reraises BuildError, TypeError, and APIError exceptions.
def getImage(path, dockerfile, tag): '''Check if an image with a given tag exists. If not, build an image from using a given dockerfile in a given path, tagging it with a given tag. No extra side effects. Handles and reraises BuildError, TypeError, and APIError exceptions. ''' image = getImageBy...
Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions.
def runContainer(image, **kwargs): '''Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions. ''' container = Non...
Get the container with the given name or ID (str). No side effects. Idempotent. Returns None if the container does not exist. Otherwise, the continer is returned
def getContainer(name_or_id): '''Get the container with the given name or ID (str). No side effects. Idempotent. Returns None if the container does not exist. Otherwise, the continer is returned''' require_str("name_or_id", name_or_id) container = None try: container = client.containers...
Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.
def containerIsRunning(name_or_id): '''Check if container with the given name or ID (str) is running. No side effects. Idempotent. Returns True if running, False if not.''' require_str("name_or_id", name_or_id) try: container = getContainer(name_or_id) # Refer to the latest status list ...
Check if a container with a given tag exists. No side-effects. Idempotent. Handles NotFound and APIError exceptions, but only reraises APIError. Returns None if the container is not found. Otherwise, returns the container.
def getContainerByTag(tag): '''Check if a container with a given tag exists. No side-effects. Idempotent. Handles NotFound and APIError exceptions, but only reraises APIError. Returns None if the container is not found. Otherwise, returns the container.''' require_str("tag", tag) container = No...
Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions.
def removeContainer(tag): '''Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions. ''' container = getContainerByTag(tag) if container: # Build an Image using the dockerfile in the path ...
Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.
def startIndyPool(**kwargs): '''Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.''' # TODO: Decide if we need a separate docker container for testing and one...
Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool container is a new running instance.
def restartIndyPool(**kwargs): '''Restart the indy_pool docker container. Idempotent. Ensures that the indy_pool container is a new running instance.''' print("Restarting...") try: stopIndyPool() startIndyPool() print("...restarted") except Exception as exc: eprint("...failed...
Special signing state where the the data for an attribute is hashed before signing :return: state to be used when signing
def signingPayloadState(self, identifier=None): """ Special signing state where the the data for an attribute is hashed before signing :return: state to be used when signing """ if self.operation.get(TXN_TYPE) == ATTRIB: d = deepcopy(super().signingPayloadStat...
Test for the directory, open old and new ledger, migrate data, rename directories
def _migrate_ledger(data_directory, old_ledger_file, new_ledger_file, serializer: MappingSerializer = None): """ Test for the directory, open old and new ledger, migrate data, rename directories """ # we should have ChunkedFileStorage implementation of the Ledger...
None roles are stored as empty strings, so the role returned as None by this function means that corresponding DID is not stored in a ledger.
def get_role(self, request: Request): """ None roles are stored as empty strings, so the role returned as None by this function means that corresponding DID is not stored in a ledger. """ idr = request.identifier return self._get_role(idr)
Handles transaction of type POOL_CONFIG :param txn:
def handleConfigTxn(self, txn) -> None: """ Handles transaction of type POOL_CONFIG :param txn: """ if get_type(txn) == POOL_CONFIG: self.writes = get_payload_data(txn)[WRITES]
Checks ledger config txns and perfomes recent one :return:
def processLedger(self) -> None: """ Checks ledger config txns and perfomes recent one :return: """ logger.debug('{} processing config ledger for any POOL_CONFIGs'.format( self), extra={"tags": ["pool-config"]}) for _, txn in self.ledger.getAllTxn(): ...
Handles transaction of type POOL_RESTART Can schedule or cancel restart to a newer version at specified time :param req:
def handleRestartRequest(self, req: Request) -> None: """ Handles transaction of type POOL_RESTART Can schedule or cancel restart to a newer version at specified time :param req: """ txn = req.operation if txn[TXN_TYPE] != POOL_RESTART: return...
Schedules node restart to a newer version :param version: version to restart to :param when: restart time
def _scheduleRestart(self, when: Union[datetime, str], failTimeout) -> None: """ Schedules node restart to a newer version :param version: version to restart to :param when: restart time """ logger.info("{}'s restarter pr...
Cancels scheduled restart :param when: time restart was scheduled to :param version: version restart scheduled for
def _cancelScheduledRestart(self, justification=None) -> None: """ Cancels scheduled restart :param when: time restart was scheduled to :param version: version restart scheduled for """ if self.scheduledAction: why_prefix = ": " why = justificati...
Callback which is called when restart time come. Writes restart record to restart log and asks node control service to perform restart :param ev_data: restart event data :param version: version to restart to
def _callRestartAgent(self, ev_data: RestartLogData, failTimeout) -> None: """ Callback which is called when restart time come. Writes restart record to restart log and asks node control service to perform restart :param ev_data: restart event data :param version: versio...