INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
** Description ** Find the image with the tag <image > and return its metadata. | def query_image_metadata(self, image, metadata_type=""):
'''**Description**
Find the image with the tag <image> and return its metadata.
**Arguments**
- image: Input image can be in the following formats: registry/repo:tag
- metadata_type: The metadata type can be on... |
** Description ** Find the image with the tag <image > and return its vulnerabilities. | def query_image_vuln(self, image, vuln_type="", vendor_only=True):
'''**Description**
Find the image with the tag <image> and return its vulnerabilities.
**Arguments**
- image: Input image can be in the following formats: registry/repo:tag
- vuln_type: Vulnerability ... |
** Description ** Delete image from the scanner. | def delete_image(self, image, force=False):
'''**Description**
Delete image from the scanner.
**Arguments**
- None
'''
_, _, image_digest = self._discover_inputimage(image)
if not image_digest:
return [False, "cannot use input image string: no... |
** Description ** Check the latest policy evaluation for an image | def check_image_evaluation(self, image, show_history=False, detail=False, tag=None, policy=None):
'''**Description**
Check the latest policy evaluation for an image
**Arguments**
- image: Input image can be in the following formats: registry/repo:tag
- show_history: ... |
** Description ** Add image registry | def add_registry(self, registry, registry_user, registry_pass, insecure=False, registry_type="docker_v2", validate=True):
'''**Description**
Add image registry
**Arguments**
- registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
- registry_user: User... |
** Description ** Update an existing image registry. | def update_registry(self, registry, registry_user, registry_pass, insecure=False, registry_type="docker_v2", validate=True):
'''**Description**
Update an existing image registry.
**Arguments**
- registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
- ... |
** Description ** Delete an existing image registry | def delete_registry(self, registry):
'''**Description**
Delete an existing image registry
**Arguments**
- registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
'''
# do some input string checking
if re.match(".*\\/.*", registry):
... |
** Description ** Find the registry and return its json description | def get_registry(self, registry):
'''**Description**
Find the registry and return its json description
**Arguments**
- registry: Full hostname/port of registry. Eg. myrepo.example.com:5000
**Success Return Value**
A JSON object representing the registry.
... |
** Description ** Create a new policy | def add_policy(self, name, rules, comment="", bundleid=None):
'''**Description**
Create a new policy
**Arguments**
- name: The name of the policy.
- rules: A list of Anchore PolicyRule elements (while creating/updating a policy, new rule IDs will be created backend s... |
** Description ** Retrieve the policy with the given id in the targeted policy bundle | def get_policy(self, policyid, bundleid=None):
'''**Description**
Retrieve the policy with the given id in the targeted policy bundle
**Arguments**
- policyid: Unique identifier associated with this policy.
- bundleid: Target bundle. If not specified, the currently a... |
** Description ** Update the policy with the given id | def update_policy(self, policyid, policy_description):
'''**Description**
Update the policy with the given id
**Arguments**
- policyid: Unique identifier associated with this policy.
- policy_description: A dictionary with the policy description.
**Success R... |
** Description ** Create a new alert | def add_alert(self, name, description=None, scope="", triggers={'failed': True, 'unscanned': True},
enabled=False, notification_channels=[]):
'''**Description**
Create a new alert
**Arguments**
- name: The name of the alert.
- description: The descp... |
** Description ** List the current set of scanning alerts. | def list_alerts(self, limit=None, cursor=None):
'''**Description**
List the current set of scanning alerts.
**Arguments**
- limit: Maximum number of alerts in the response.
- cursor: An opaque string representing the current position in the list of alerts. It's provi... |
** Description ** Update the alert with the given id | def update_alert(self, alertid, alert_description):
'''**Description**
Update the alert with the given id
**Arguments**
- alertid: Unique identifier associated with this alert.
- alert_description: A dictionary with the alert description.
**Success Return Va... |
** Description ** Delete the alert with the given id | def delete_alert(self, policyid):
'''**Description**
Delete the alert with the given id
**Arguments**
- alertid: Unique identifier associated with this alert.
'''
url = self.url + '/api/scanning/v1/alerts/' + policyid
res = requests.delete(url, headers=se... |
** Description ** List all subscriptions | def list_subscription(self):
'''**Description**
List all subscriptions
**Arguments**
- None
**Success Return Value**
A JSON object representing the list of subscriptions.
'''
url = self.url + "/api/scanning/v1/anchore/subscriptions"
r... |
** Description ** List runtime containers | def list_runtime(self, scope="", skip_policy_evaluation=True, start_time=None, end_time=None):
'''**Description**
List runtime containers
**Arguments**
- scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: 'host.domain = ... |
None means system default | def addSourceAddr(self, addr):
"""None means 'system default'"""
try:
self._multiInSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._makeMreq(addr))
except socket.error: # if 1 interface has more than 1 address, exception is raised for the second
pass
... |
Method sleeps if nothing to do | def _sendPendingMessages(self):
"""Method sleeps, if nothing to do"""
if len(self._queue) == 0:
time.sleep(0.1)
return
msg = self._queue.pop(0)
if msg.canSend():
self._sendMsg(msg)
msg.refresh()
if not (msg.isFinished()):
... |
Set callback which will be called when new service appeared online and sent Hi message | def setRemoteServiceHelloCallback(self, cb, types=None, scopes=None):
"""Set callback, which will be called when new service appeared online
and sent Hi message
typesFilter and scopesFilter might be list of types and scopes.
If filter is set, callback is called only for Hello messages,
... |
cleans up and stops the discovery server | def stop(self):
'cleans up and stops the discovery server'
self.clearRemoteServices()
self.clearLocalServices()
self._stopThreads()
self._serverStarted = False |
send Bye messages for the services and remove them | def clearLocalServices(self):
'send Bye messages for the services and remove them'
for service in list(self._localServices.values()):
self._sendBye(service)
self._localServices.clear() |
search for services given the TYPES and SCOPES in a given TIMEOUT | def searchServices(self, types=None, scopes=None, timeout=3):
'search for services given the TYPES and SCOPES in a given TIMEOUT'
if not self._serverStarted:
raise Exception("Server not started")
self._sendProbe(types, scopes)
time.sleep(timeout)
return self._filt... |
Publish a service with the given TYPES SCOPES and XAddrs ( service addresses ) | def publishService(self, types, scopes, xAddrs):
"""Publish a service with the given TYPES, SCOPES and XAddrs (service addresses)
if xAddrs contains item, which includes {ip} pattern, one item per IP addres will be sent
"""
if not self._serverStarted:
raise Exception("Serve... |
construct a a raw SOAP XML string given a prepared SoapEnvelope object | def createSOAPMessage(env):
"construct a a raw SOAP XML string, given a prepared SoapEnvelope object"
if env.getAction() == ACTION_PROBE:
return createProbeMessage(env)
if env.getAction() == ACTION_PROBE_MATCH:
return createProbeMatchMessage(env)
if env.getAction() == ACTION_RESOLVE:
... |
parse raw XML data string return a ( minidom ) xml document | def parseSOAPMessage(data, ipAddr):
"parse raw XML data string, return a (minidom) xml document"
try:
dom = minidom.parseString(data)
except Exception:
#print('Failed to parse message from %s\n"%s": %s' % (ipAddr, data, ex), file=sys.stderr)
return None
if dom.getElementsByTagN... |
Discover systems using WS - Discovery | def discover(scope, loglevel, capture):
"Discover systems using WS-Discovery"
if loglevel:
level = getattr(logging, loglevel, None)
if not level:
print("Invalid log level '%s'" % loglevel)
return
logger.setLevel(level)
run(scope=scope, capture=capture) |
Return the manager that handles the relation from this instance to the tagged_item class. If content_object on the tagged_item class is defined as a ParentalKey this will be a DeferringRelatedManager which allows writing related objects without committing them to the database. | def get_tagged_item_manager(self):
"""Return the manager that handles the relation from this instance to the tagged_item class.
If content_object on the tagged_item class is defined as a ParentalKey, this will be a
DeferringRelatedManager which allows writing related objects without committing t... |
Return a serialised version of the model s fields which exist as local database columns ( i. e. excluding m2m and incoming foreign key relations ) | def get_serializable_data_for_fields(model):
"""
Return a serialised version of the model's fields which exist as local database
columns (i.e. excluding m2m and incoming foreign key relations)
"""
pk_field = model._meta.pk
# If model is a child via multitable inheritance, use parent's pk
whi... |
Return a list of RelatedObject records for child relations of the given model including ones attached to ancestors of the model | def get_all_child_relations(model):
"""
Return a list of RelatedObject records for child relations of the given model,
including ones attached to ancestors of the model
"""
return [
field for field in model._meta.get_fields()
if isinstance(field.remote_field, ParentalKey)
] |
Return a list of ParentalManyToManyFields on the given model including ones attached to ancestors of the model | def get_all_child_m2m_relations(model):
"""
Return a list of ParentalManyToManyFields on the given model,
including ones attached to ancestors of the model
"""
return [
field for field in model._meta.get_fields()
if isinstance(field, ParentalManyToManyField)
] |
Save the model and commit all child relations. | def save(self, **kwargs):
"""
Save the model and commit all child relations.
"""
child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(self)]
child_m2m_field_names = [field.name for field in get_all_child_m2m_relations(self)]
update_fields = ... |
Build an instance of this model from the JSON - like structure passed in recursing into related objects as required. If check_fks is true it will check whether referenced foreign keys still exist in the database. - dangling foreign keys on related objects are dealt with by either nullifying the key or dropping the rela... | def from_serializable_data(cls, data, check_fks=True, strict_fks=False):
"""
Build an instance of this model from the JSON-like structure passed in,
recursing into related objects as required.
If check_fks is true, it will check whether referenced foreign keys still
exist in the ... |
This clean method will check for unique_together condition | def validate_unique(self):
'''This clean method will check for unique_together condition'''
# Collect unique_checks and to run from all the forms.
all_unique_checks = set()
all_date_checks = set()
forms_to_delete = self.deleted_forms
valid_forms = [form for form in self.f... |
Return True if data differs from initial. | def has_changed(self):
"""Return True if data differs from initial."""
# Need to recurse over nested formsets so that the form is saved if there are changes
# to child forms but not the parent
if self.formsets:
for formset in self.formsets.values():
for form ... |
Create a DeferringRelatedManager class that wraps an ordinary RelatedManager with deferring behaviour: any updates to the object set ( via e. g. add () or clear () ) are written to a holding area rather than committed to the database immediately. Writing to the database is deferred until the model is saved. | def create_deferring_foreign_related_manager(related, original_manager_cls):
"""
Create a DeferringRelatedManager class that wraps an ordinary RelatedManager
with 'deferring' behaviour: any updates to the object set (via e.g. add() or clear())
are written to a holding area rather than committed to the d... |
Sort a list of objects on the given fields. The field list works analogously to queryset. order_by ( * fields ): each field is either a property of the object or is prefixed by - ( e. g. - name ) to indicate reverse ordering. | def sort_by_fields(items, fields):
"""
Sort a list of objects on the given fields. The field list works analogously to
queryset.order_by(*fields): each field is either a property of the object,
or is prefixed by '-' (e.g. '-name') to indicate reverse ordering.
"""
# To get the desired behaviour,... |
Returns the address with a valid checksum attached. | def with_valid_checksum(self):
# type: () -> Address
"""
Returns the address with a valid checksum attached.
"""
return Address(
trytes=self.address + self._generate_checksum(),
# Make sure to copy all of the ancillary attributes, too!
balance... |
Generates the correct checksum for this address. | def _generate_checksum(self):
# type: () -> AddressChecksum
"""
Generates the correct checksum for this address.
"""
checksum_trits = [] # type: MutableSequence[int]
sponge = Kerl()
sponge.absorb(self.address.as_trits())
sponge.squeeze(checksum_trits)
... |
Executes the command and ( optionally ) returns an exit code ( used by the shell to determine if the application exited cleanly ). | def execute(self, api, **arguments):
# type: (Iota, **Any) -> Optional[int]
"""
Executes the command and (optionally) returns an exit code (used by
the shell to determine if the application exited cleanly).
:param api:
The API object used to communicate with the node... |
Executes the command from a collection of arguments ( e. g.: py: data sys. argv ) and returns the exit code. | def run_from_argv(self, argv=None):
# type: (Optional[tuple]) -> int
"""
Executes the command from a collection of arguments (e.g.,
:py:data`sys.argv`) and returns the exit code.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults... |
Parses arguments for the command. | def parse_argv(self, argv=None):
# type: (Optional[tuple]) -> dict
"""
Parses arguments for the command.
:param argv:
Arguments to pass to the argument parser.
If ``None``, defaults to ``sys.argv[1:]``.
"""
arguments = vars(self.create_argument_pa... |
Returns the argument parser that will be used to interpret arguments and options from argv. | def create_argument_parser(self):
# type: () -> ArgumentParser
"""
Returns the argument parser that will be used to interpret
arguments and options from argv.
"""
parser = ArgumentParser(
description=self.__doc__,
epilog='PyOTA v{version}'.format(v... |
Prompts the user to enter their seed via stdin. | def prompt_for_seed():
# type: () -> Seed
"""
Prompts the user to enter their seed via stdin.
"""
seed = secure_input(
'Enter seed and press return (typing will not be shown).\n'
'If no seed is specified, a random one will be used instead.\n'
)
... |
Normalizes a hash converting it into a sequence of integers ( not trits! ) suitable for use in signature generation/ validation. | def normalize(hash_):
# type: (Hash) -> List[List[int]]
"""
"Normalizes" a hash, converting it into a sequence of integers
(not trits!) suitable for use in signature generation/validation.
The hash is divided up into 3 parts, each of which is "balanced"
(sum of all the values is equal to zero).... |
Returns whether a sequence of signature fragments is valid. | def validate_signature_fragments(
fragments,
hash_,
public_key,
sponge_type=Kerl,
):
# type: (Sequence[TryteString], Hash, TryteString, type) -> bool
"""
Returns whether a sequence of signature fragments is valid.
:param fragments:
Sequence of signature fragments (... |
Generates a single key. | def get_key(self, index, iterations):
# type: (int, int) -> PrivateKey
"""
Generates a single key.
:param index:
The key index.
:param iterations:
Number of transform iterations to apply to the key, also
known as security level.
M... |
Generates the key associated with the specified address. | def get_key_for(self, address):
"""
Generates the key associated with the specified address.
Note that this method will generate the wrong key if the input
address was generated from a different key!
"""
return self.get_key(
index=address.key_index,
... |
Generates and returns one or more keys at the specified index ( es ). | def get_keys(self, start, count=1, step=1, iterations=1):
# type: (int, int, int, int) -> List[PrivateKey]
"""
Generates and returns one or more keys at the specified
index(es).
This is a one-time operation; if you want to create lots of keys
across multiple contexts, co... |
Creates a generator that can be used to progressively generate new keys. | def create_iterator(self, start=0, step=1, security_level=1):
# type: (int, int, int) -> KeyIterator
"""
Creates a generator that can be used to progressively generate
new keys.
:param start:
Starting index.
Warning: This method may take awhile to reset ... |
Prepares the hash sponge for the generator. | def _create_sponge(self, index):
# type: (int) -> Kerl
"""
Prepares the hash sponge for the generator.
"""
seed = self.seed_as_trits[:]
sponge = Kerl()
sponge.absorb(add_trits(seed, trits_from_int(index)))
# Squeeze all of the trits out of the sponge and... |
Absorb trits into the sponge. | def absorb(self, trits, offset=0, length=None):
# type: (Sequence[int], Optional[int], Optional[int]) -> None
"""
Absorb trits into the sponge.
:param trits:
Sequence of trits to absorb.
:param offset:
Starting offset in ``trits``.
:param length... |
Squeeze trits from the sponge. | def squeeze(self, trits, offset=0, length=HASH_LENGTH):
# type: (MutableSequence[int], Optional[int], Optional[int]) -> None
"""
Squeeze trits from the sponge.
:param trits:
Sequence that the squeezed trits will be copied to.
Note: this object will be modified!
... |
Transforms internal state. | def _transform(self):
# type: () -> None
"""
Transforms internal state.
"""
# Copy some values locally so we can avoid global lookups in the
# inner loop.
#
# References:
#
# - https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_... |
Generates one or more key digests from the seed. | def get_digests(
self,
index=0,
count=1,
security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
):
# type: (int, int, int) -> dict
"""
Generates one or more key digests from the seed.
Digests are safe to share; use them to generate mu... |
Generates one or more private keys from the seed. | def get_private_keys(
self,
index=0,
count=1,
security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
):
# type: (int, int, int) -> dict
"""
Generates one or more private keys from the seed.
As the name implies, private keys should not... |
Prepares a bundle that authorizes the spending of IOTAs from a multisig address. | def prepare_multisig_transfer(
self,
transfers, # type: Iterable[ProposedTransaction]
multisig_input, # type: MultisigAddress
change_address=None, # type: Optional[Address]
):
# type: (...) -> dict
"""
Prepares a bundle that authorizes the s... |
Adds two sequences of trits together. | def add_trits(left, right):
# type: (Sequence[int], Sequence[int]) -> List[int]
"""
Adds two sequences of trits together.
The result is a list of trits equal in length to the longer of the
two sequences.
.. note::
Overflow is possible.
For example, ``add_trits([1], [1])`` retu... |
Returns a trit representation of an integer value. | def trits_from_int(n, pad=1):
# type: (int, Optional[int]) -> List[int]
"""
Returns a trit representation of an integer value.
:param n:
Integer value to convert.
:param pad:
Ensure the result has at least this many trits.
References:
- https://dev.to/buntine/the-balanced... |
Adds two individual trits together. | def _add_trits(left, right):
# type: (int, int) -> int
"""
Adds two individual trits together.
The result is always a single trit.
"""
res = left + right
return res if -2 < res < 2 else (res < 0) - (res > 0) |
Adds two trits together with support for a carry trit. | def _full_add_trits(left, right, carry):
# type: (int, int, int) -> Tuple[int, int]
"""
Adds two trits together, with support for a carry trit.
"""
sum_both = _add_trits(left, right)
cons_left = _cons_trits(left, right)
cons_right = _cons_trits(sum_both, carry)
return _add_trits(sum_bot... |
Outputs the user s seed to stdout along with lots of warnings about security. | def output_seed(seed):
# type: (Seed) -> None
"""
Outputs the user's seed to stdout, along with lots of warnings
about security.
"""
print(
'WARNING: Anyone who has your seed can spend your IOTAs! '
'Clear the screen after recording your seed!'
)
compat.input('')
prin... |
Attaches the specified transactions ( trytes ) to the Tangle by doing Proof of Work. You need to supply branchTransaction as well as trunkTransaction ( basically the tips which you re going to validate and reference with this transaction ) - both of which you ll get through the getTransactionsToApprove API call. | def attach_to_tangle(
self,
trunk_transaction, # type: TransactionHash
branch_transaction, # type: TransactionHash
trytes, # type: Iterable[TryteString]
min_weight_magnitude=None, # type: Optional[int]
):
# type: (...) -> dict
"""
... |
Find the transactions which match the specified input and return. | def find_transactions(
self,
bundles=None, # type: Optional[Iterable[BundleHash]]
addresses=None, # type: Optional[Iterable[Address]]
tags=None, # type: Optional[Iterable[Tag]]
approvees=None, # type: Optional[Iterable[TransactionHash]]
):
# ty... |
Similar to: py: meth: get_inclusion_states. Returns the confirmed balance which a list of addresses have at the latest confirmed milestone. | def get_balances(self, addresses, threshold=100):
# type: (Iterable[Address], int) -> dict
"""
Similar to :py:meth:`get_inclusion_states`. Returns the
confirmed balance which a list of addresses have at the latest
confirmed milestone.
In addition to the balances, it also... |
Get the inclusion states of a set of transactions. This is for determining if a transaction was accepted and confirmed by the network or not. You can search for multiple tips ( and thus milestones ) to get past inclusion states of transactions. | def get_inclusion_states(self, transactions, tips):
# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict
"""
Get the inclusion states of a set of transactions. This is for
determining if a transaction was accepted and confirmed by the
network or not. You can sea... |
More comprehensive version of: py: meth: get_transfers that returns addresses and account balance in addition to bundles. | def get_account_data(self, start=0, stop=None, inclusion_states=False, security_level=None):
# type: (int, Optional[int], bool, Optional[int]) -> dict
"""
More comprehensive version of :py:meth:`get_transfers` that
returns addresses and account balance in addition to bundles.
Th... |
Gets all possible inputs of a seed and returns them along with the total balance. | def get_inputs(
self,
start=0,
stop=None,
threshold=None,
security_level=None,
):
# type: (int, Optional[int], Optional[int], Optional[int]) -> dict
"""
Gets all possible inputs of a seed and returns them, along with
the tot... |
Generates one or more new addresses from the seed. | def get_new_addresses(
self,
index=0,
count=1,
security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
checksum=False,
):
# type: (int, Optional[int], int, bool) -> dict
"""
Generates one or more new addresses from the seed.
... |
Returns all transfers associated with the seed. | def get_transfers(self, start=0, stop=None, inclusion_states=False):
# type: (int, Optional[int], bool) -> dict
"""
Returns all transfers associated with the seed.
:param start:
Starting key index.
:param stop:
Stop before this index.
Note t... |
Prepares transactions to be broadcast to the Tangle by generating the correct bundle as well as choosing and signing the inputs ( for value transfers ). | def prepare_transfer(
self,
transfers, # type: Iterable[ProposedTransaction]
inputs=None, # type: Optional[Iterable[Address]]
change_address=None, # type: Optional[Address]
security_level=None, # type: Optional[int]
):
# type: (...) -> dict
... |
Promotes a transaction by adding spam on top of it. | def promote_transaction(
self,
transaction,
depth=3,
min_weight_magnitude=None,
):
# type: (TransactionHash, int, Optional[int]) -> dict
"""
Promotes a transaction by adding spam on top of it.
:return:
Dict with the followi... |
Takes a tail transaction hash as input gets the bundle associated with the transaction and then replays the bundle by attaching it to the Tangle. | def replay_bundle(
self,
transaction,
depth=3,
min_weight_magnitude=None,
):
# type: (TransactionHash, int, Optional[int]) -> dict
"""
Takes a tail transaction hash as input, gets the bundle
associated with the transaction and then repl... |
Prepares a set of transfers and creates the bundle then attaches the bundle to the Tangle and broadcasts and stores the transactions. | def send_transfer(
self,
transfers, # type: Iterable[ProposedTransaction]
depth=3, # type: int
inputs=None, # type: Optional[Iterable[Address]]
change_address=None, # type: Optional[Address]
min_weight_magnitude=None, # type: Optional[int]
... |
Attaches transaction trytes to the Tangle then broadcasts and stores them. | def send_trytes(self, trytes, depth=3, min_weight_magnitude=None):
# type: (Iterable[TransactionTrytes], int, Optional[int]) -> dict
"""
Attaches transaction trytes to the Tangle, then broadcasts and
stores them.
:param trytes:
Transaction encoded as a tryte sequence... |
Given a URI returns a properly - configured adapter instance. | def resolve_adapter(uri):
# type: (AdapterSpec) -> BaseAdapter
"""
Given a URI, returns a properly-configured adapter instance.
"""
if isinstance(uri, BaseAdapter):
return uri
parsed = compat.urllib_parse.urlsplit(uri) # type: SplitResult
if not parsed.scheme:
raise with_c... |
Sends an API request to the node. | def send_request(self, payload, **kwargs):
# type: (dict, dict) -> dict
"""
Sends an API request to the node.
:param payload:
JSON payload.
:param kwargs:
Additional keyword arguments for the adapter.
:return:
Decoded response from t... |
Sends a message to the instance s logger if configured. | def _log(self, level, message, context=None):
# type: (int, Text, Optional[dict]) -> None
"""
Sends a message to the instance's logger, if configured.
"""
if self._logger:
self._logger.log(level, message, extra={'context': context or {}}) |
Sends the actual HTTP request. | def _send_http_request(self, url, payload, method='post', **kwargs):
# type: (Text, Optional[Text], Text, dict) -> Response
"""
Sends the actual HTTP request.
Split into its own method so that it can be mocked during unit
tests.
"""
kwargs.setdefault(
... |
Interprets the HTTP response from the node. | def _interpret_response(self, response, payload, expected_status):
# type: (Response, dict, Container[int]) -> dict
"""
Interprets the HTTP response from the node.
:param response:
The response object received from
:py:meth:`_send_http_request`.
:param p... |
Sets the response that the adapter will return for the specified command. | def seed_response(self, command, response):
# type: (Text, dict) -> MockAdapter
"""
Sets the response that the adapter will return for the specified
command.
You can seed multiple responses per command; the adapter will
put them into a FIFO queue. When a request comes i... |
Absorbs a digest into the sponge. | def add_digest(self, digest):
# type: (Digest) -> None
"""
Absorbs a digest into the sponge.
.. important::
Keep track of the order that digests are added!
To spend inputs from a multisig address, you must provide
the private keys in the same order!
... |
Returns the new multisig address. | def get_address(self):
# type: () -> MultisigAddress
"""
Returns the new multisig address.
Note that you can continue to add digests after extracting an
address; the next address will use *all* of the digests that
have been added so far.
"""
if not self._... |
Generates and returns one or more addresses at the specified index ( es ). | def get_addresses(self, start, count=1, step=1):
# type: (int, int, int) -> List[Address]
"""
Generates and returns one or more addresses at the specified
index(es).
This is a one-time operation; if you want to create lots of
addresses across multiple contexts, consider ... |
Creates an iterator that can be used to progressively generate new addresses. | def create_iterator(self, start=0, step=1):
# type: (int, int) -> Generator[Address, None, None]
"""
Creates an iterator that can be used to progressively generate new
addresses.
:param start:
Starting index.
Warning: This method may take awhile to reset... |
Generates an address from a private key digest. | def address_from_digest(digest):
# type: (Digest) -> Address
"""
Generates an address from a private key digest.
"""
address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: List[int]
sponge = Kerl()
sponge.absorb(digest.as_trits())
sponge.squeeze(a... |
Generates a new address. | def _generate_address(self, key_iterator):
# type: (KeyIterator) -> Address
"""
Generates a new address.
Used in the event of a cache miss.
"""
if self.checksum:
return (
self.address_from_digest(
digest=self._get_digest(ke... |
Finds transactions matching the specified criteria fetches the corresponding trytes and converts them into Transaction objects. | def find_transaction_objects(adapter, **kwargs):
# type: (BaseAdapter, **Iterable) -> List[Transaction]
"""
Finds transactions matching the specified criteria, fetches the
corresponding trytes and converts them into Transaction objects.
"""
ft_response = FindTransactionsCommand(adapter)(**kwargs... |
Scans the Tangle for used addresses. | def iter_used_addresses(
adapter, # type: BaseAdapter
seed, # type: Seed
start, # type: int
security_level=None, # type: Optional[int]
):
# type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None]
"""
Scans the Tangle for used addresses.
This is ba... |
Given a set of transaction hashes returns the corresponding bundles sorted by tail transaction timestamp. | def get_bundles_from_transaction_hashes(
adapter,
transaction_hashes,
inclusion_states,
):
# type: (BaseAdapter, Iterable[TransactionHash], bool) -> List[Bundle]
"""
Given a set of transaction hashes, returns the corresponding bundles,
sorted by tail transaction timestamp.
""... |
Adds inputs to spend in the bundle. | def add_inputs(self, inputs):
# type: (Iterable[MultisigAddress]) -> None
"""
Adds inputs to spend in the bundle.
Note that each input may require multiple transactions, in order to
hold the entire signature.
:param inputs:
MultisigAddresses to use as the inputs for this bundle.
N... |
Determines which codec to use for the specified encoding. | def check_trytes_codec(encoding):
"""
Determines which codec to use for the specified encoding.
References:
- https://docs.python.org/3/library/codecs.html#codecs.register
"""
if encoding == AsciiTrytesCodec.name:
return AsciiTrytesCodec.get_codec_info()
elif encoding == AsciiTryt... |
Returns information used by the codecs library to configure the codec for use. | def get_codec_info(cls):
"""
Returns information used by the codecs library to configure the
codec for use.
"""
codec = cls()
codec_info = {
'encode': codec.encode,
'decode': codec.decode,
}
# In Python 2, all codecs are made equa... |
Encodes a byte string into trytes. | def encode(self, input, errors='strict'):
"""
Encodes a byte string into trytes.
"""
if isinstance(input, memoryview):
input = input.tobytes()
if not isinstance(input, (binary_type, bytearray)):
raise with_context(
exc=TypeError(
... |
Decodes a tryte string into bytes. | def decode(self, input, errors='strict'):
"""
Decodes a tryte string into bytes.
"""
if isinstance(input, memoryview):
input = input.tobytes()
if not isinstance(input, (binary_type, bytearray)):
raise with_context(
exc=TypeError(
... |
Find addresses matching the command parameters. | def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
"""
Find addresses matching the command parameters.
"""
generator = AddressGenerator(seed, security_level, checksum)
if count is None:
... |
Adds a route to the wrapper. | def add_route(self, command, adapter):
# type: (Text, AdapterSpec) -> RoutingWrapper
"""
Adds a route to the wrapper.
:param command:
The name of the command to route (e.g., "attachToTangle").
:param adapter:
The adapter object or URI to route requests t... |
Creates a Transaction object from a sequence of trytes. | def from_tryte_string(cls, trytes, hash_=None):
# type: (TrytesCompatible, Optional[TransactionHash]) -> Transaction
"""
Creates a Transaction object from a sequence of trytes.
:param trytes:
Raw trytes. Should be exactly 2673 trytes long.
:param hash_:
... |
Returns a JSON - compatible representation of the object. | def as_json_compatible(self):
# type: () -> dict
"""
Returns a JSON-compatible representation of the object.
References:
- :py:class:`iota.json.JsonEncoder`.
"""
return {
'hash_': self.hash,
'signature_message_fragment': self.signature_me... |
Returns a TryteString representation of the transaction. | def as_tryte_string(self):
# type: () -> TransactionTrytes
"""
Returns a TryteString representation of the transaction.
"""
return TransactionTrytes(
self.signature_message_fragment
+ self.address.address
+ self.value_as_trytes
+ se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.