PolySwarm Client Source-Based Documentation¶
API Reference¶
This page contains auto-generated API reference documentation 1.
conftest
¶
ambassador
¶
Submodules¶
ambassador.__main__
¶
Module Contents¶
-
ambassador.__main__.
choose_backend
(backend)[source]¶ -
Resolves amabassador name string to implementation
- Parameters
backend (str) – Name of the backend to load, either one of the predefined implementations or the name of a module to load (module:ClassName syntax or default of module:Ambassador)
- Returns
Ambassador class of the selected implementation
- Return type
(Class)
- Raises
(Exception) – If backend is not found
ambassador.eicar
¶
Module Contents¶
-
class
ambassador.eicar.
Ambassador
(client, testing=0, chains=None, watchdog=0, submission_rate=30)[source]¶ Bases:
polyswarmclient.abstractambassador.AbstractAmbassador
Ambassador which submits the EICAR test file
ambassador.filesystem
¶
Module Contents¶
-
class
ambassador.filesystem.
Ambassador
(client, testing=0, chains=None, watchdog=0, submission_rate=30)[source]¶ Bases:
polyswarmclient.abstractambassador.AbstractAmbassador
Ambassador which submits artifacts from a directory
worker
¶
Submodules¶
worker.__main__
¶
Module Contents¶
-
worker.__main__.
choose_backend
(backend)[source]¶ -
Resolves scanner name string to implementation
- Parameters
backend (str) – Name of the backend to load, either one of the predefined implementations or the name of a module
load (to) –
(module – ClassName syntax or default of module:Scanner)
- Returns
Scanner class of the selected implementation
- Return type
(Class)
- Raises
(Exception) – If backend is not found
worker.base
¶
Module Contents¶
-
class
worker.base.
RateLimitAggregate
(redis, queue, daily_rate_limit, hourly_rate_limit, minutely_rate_limit, secondly_rate_limit)[source]¶ Bases:
polyswarmclient.ratelimit.abstractratelimit.AbstractRateLimit
worker.exceptions
¶
Module Contents¶
-
class
worker.exceptions.
ExpiredException
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Worker skipped scanning some artifact due to the bounty expiring before getting scanned. Seen when the worker was down for a period of time, or when there aren’t enough workers to keep up with load.
-
class
worker.exceptions.
EmptyJobsQueueException
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Worker Queue is empty
Package Contents¶
-
class
worker.
Worker
(redis_addr, queue, task_count=0, download_limit=0, scan_limit=0, api_key=None, testing=0, scanner=None, scan_time_requirement=0, daily_rate_limit=None, hourly_rate_limit=None, minutely_rate_limit=None, secondly_rate_limit=None, allow_key_over_http=False)[source]¶ -
run
(self)¶
-
start
(self, loop: asyncio.AbstractEventLoop)¶
-
setup_synchronization
(self, loop: asyncio.AbstractEventLoop)¶
-
setup_graceful_shutdown
(self, loop: asyncio.AbstractEventLoop)¶
-
handle_signal
(self)¶
-
get_remaining_time
(self, job: JobRequest)¶
-
rate_limit_respond
(self, job: JobRequest)¶
-
is_key_secure
(self, job: JobRequest)¶
-
balancemanager
¶
Submodules¶
balancemanager.__main__
¶
Module Contents¶
-
balancemanager.__main__.
cli
(log, client_log, log_format)[source]¶ -
Entrypoint for the balance manager driver
-
balancemanager.__main__.
deposit
(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, all, amount)[source]¶ -
Deposit NCT into a sidechain
-
balancemanager.__main__.
withdraw
(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, all, amount)[source]¶ -
Withdraw NCT from a sidechain
-
balancemanager.__main__.
deposit_stake
(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, all, chain, amount)[source]¶ -
Deposit NCT into the ArbiterStaking contract
-
balancemanager.__main__.
withdraw_stake
(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, all, chain, amount)[source]¶ -
Withdraw NCT from the ArbiterStaking contract
-
balancemanager.__main__.
maintain
(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, maximum, withdraw_target, confirmations, minimum, refill_amount)[source]¶ -
Maintain min/max NCT balance in sidechain
Package Contents¶
-
balancemanager.
convert
(client, denomination, amount)[source]¶ -
Convert the amount from it's original precision to 18 decimals
-
balancemanager.
convert_from
(client, denomination, amount)[source]¶ -
Convert the amount from 18 decimals to the dedsired precision
-
class
balancemanager.
BalanceManager
(client, denomination, transfer_all, amount, testing=0, chains=None)[source]¶ Bases:
object
Balance manager is used for single transfer events in either direction. Create a client, choose a chain and amount then run it.
-
class
balancemanager.
Deposit
(client, denomination, transfer_all, amount, testing=0)[source]¶ Bases:
balancemanager.BalanceManager
Deposit only version of Balance Manager
-
class
balancemanager.
Withdraw
(client, denomination, transfer_all, amount, testing=0)[source]¶ Bases:
balancemanager.BalanceManager
Withdraw only version of Balance Manager
-
class
balancemanager.
DepositStake
(client, denomination, transfer_all, amount, testing=0, chain='side')[source]¶ Bases:
balancemanager.BalanceManager
Deposit only version of Balance Manager
-
class
balancemanager.
WithdrawStake
(client, denomination, transfer_all, amount, testing=0, chain='side')[source]¶ Bases:
balancemanager.BalanceManager
Withdraw only version of Balance Manager
-
class
balancemanager.
Maintainer
(client, denomination, confirmations, minimum, refill_amount, maximum, withdraw_target, testing=0)[source]¶ Bases:
object
This class maintains a balance on the sidechain. It requires a base setup of a minimum balance. Optionally, it can take a maximum balance, so that earnings can automatically be transferred back to the homechain.
-
class
balancemanager.
ViewBalance
(client, denomination, chain)[source]¶ Bases:
object
ViewBalance retrieves the NCT balance from a chain Create a client, choose a chain and amount then run it.
-
class
balancemanager.
ViewStake
[source]¶ Bases:
balancemanager.ViewBalance
arbiter
¶
Subpackages¶
arbiter.verbatimdb
¶
Submodules¶
arbiter.verbatimdb.__main__
¶arbiter.verbatimdb.db
¶Submodules¶
arbiter.__main__
¶
Module Contents¶
-
arbiter.__main__.
choose_backend
(backend)[source]¶ -
Resolves arbiter name string to implementation
- Parameters
backend (str) – Name of the backend to load, either one of the predefined implementations or the name of a module to load (module:ClassName syntax or default of module:Arbiter)
- Returns
Arbiter class of the selected implementation
- Return type
(Class)
- Raises
(Exception) – If backend is not found
arbiter.clamav
¶
Module Contents¶
-
class
arbiter.clamav.
Arbiter
(client, testing=0, scanner=None, chains=None, artifact_types=None)[source]¶ Bases:
polyswarmclient.abstractarbiter.AbstractArbiter
Arbiter which scans samples through clamd.
Re-uses the scanner from the clamav microengine
- Parameters
client (Client) – Client to use
testing (int) – How many test bounties to respond to
chains (set[str]) – Chain(s) to operate on
arbiter.eicar
¶
Module Contents¶
-
class
arbiter.eicar.
Arbiter
(client, testing=0, scanner=None, chains=None, artifact_types=None)[source]¶ Bases:
polyswarmclient.abstractarbiter.AbstractArbiter
Arbiter which matches hashes to a database of known samples
arbiter.producer
¶
Module Contents¶
arbiter.verbatim
¶
Module Contents¶
-
class
arbiter.verbatim.
Arbiter
(client, testing=0, scanner=None, chains=None, artifact_types=None)[source]¶ Bases:
polyswarmclient.abstractarbiter.AbstractArbiter
Arbiter which matches hashes to a database of known samples
polyswarmclient
¶
Subpackages¶
polyswarmclient.ethereum
¶
Subpackages¶
polyswarmclient.ethereum.bountiesclient
¶polyswarmclient.ethereum.bountiesclient.base
¶polyswarmclient.ethereum.bountiesclient.transaction
¶-
class
polyswarmclient.ethereum.bountiesclient.transaction.
PostBountyTransaction
(client, artifact_type, amount, bounty_fee, artifact_uri, num_artifacts, duration, bloom_, metadata)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.ethereum.bountiesclient.transaction.
PostAssertionTransaction
(client, bounty_guid, bid, assertion_fee, mask, commitment)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.ethereum.bountiesclient.transaction.
RevealAssertionTransaction
(client, bounty_guid, index, nonce, verdicts, metadata)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.ethereum.bountiesclient.transaction.
PostVoteTransaction
(client, bounty_guid, votes, valid_bloom)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
polyswarmclient.ethereum.transaction
¶polyswarmclient.ethereum.transaction.base
¶-
polyswarmclient.ethereum.transaction.base.
LOG_MSG_ENGINE_TOO_SLOW
= PLEASE REVIEW YOUR SCANNING LOGIC.[source]¶ Bounty inactive errors indicate that the microengine received the bounty, but was unable to respond to the bounty within the time window. Such errors are considered fatal during testing so you can easily identify them. If your engine is unable to respond within the time window on the live PolySwarm network, you risk losing the bid amount of the bounty at hand. We strongly encourage you to review your artifact scan process to identify areas where engine speed can be improved.
-
class
polyswarmclient.ethereum.transaction.base.
EthereumTransaction
(client, verifiers)[source]¶ Used to verify and post groups of transactions that make up a specific action.
For instance, when approving some funds to move, and calling a contract function that will consumer them.
-
__sign_transactions
(self, transactions)[source]¶ Sign a set of transactions
- Parameters
transactions (List[Transaction]) – The transactions to sign
- Returns
The signed transactions
- Return type
List[Transaction]
-
has_required_event
(self, transaction_events)[source]¶ Checks for existence of events in transaction logs, ensuring successful completion
- Returns
True if the required event was in the list, false otherwise
-
polyswarmclient.ethereum.transaction.noncemanager
¶-
class
polyswarmclient.ethereum.transaction.
EthereumTransaction
(client, verifiers)[source]¶ Used to verify and post groups of transactions that make up a specific action.
For instance, when approving some funds to move, and calling a contract function that will consumer them.
-
__sign_transactions
(self, transactions)¶ Sign a set of transactions
- Parameters
transactions (List[Transaction]) – The transactions to sign
- Returns
The signed transactions
- Return type
List[Transaction]
-
has_required_event
(self, transaction_events)¶ Checks for existence of events in transaction logs, ensuring successful completion
- Returns
True if the required event was in the list, false otherwise
-
get_path
(self)¶ Get the path of the route to build this transaction
- Returns
Polyswarmd path to get the transaction data
- Return type
str
-
get_body
(self)¶ Build the payload to send to polyswarmd :returns: Dict payload
-
verify
(self, transactions)¶ Check the given transactions against known expectations
- Parameters
transactions (list) –
- Returns
True if transactions match expectations. False otherwise
- Return type
(bool)
-
-
class
polyswarmclient.ethereum.transaction.
NonceManager
(client, chain)[source]¶ Manages the nonce for some Ethereum chain
-
static
find_gaps
(nonces)¶ Finds any gaps between base nonce and the last nonce in the given nonces list.
- Parameters
nonces (list[int]) – list of nonces being checked
- Returns
(list[int]): Any missing nonces between base_nonce and the last given nonce
-
static
Submodules¶
polyswarmclient.ethereum.balanceclient
¶polyswarmclient.ethereum.bloom
¶-
class
polyswarmclient.ethereum.bloom.
BloomFilter
(value=0)[source]¶ Bases:
numbers.Number
-
add
(self, value)[source]¶ Add a single byte value to the Bloom filter.
- Parameters
value (bytes) – Byte encoded value to add to Bloom filter.
-
extend
(self, iterable)[source]¶ Add an iterable of byte values to the bloom filter.
- Parameters
iterable (Iterable[bytes]) – Iterable of byte values.
-
classmethod
from_iterable
(cls, iterable)[source]¶ Instantiate a bloom filter from a given iterable.
- Parameters
iterable (Iterable[bytes]) – Iterable of byte values.
- Returns
Instantiated BloomFilter.
- Return type
-
static
get_bloom_bits
(value)[source]¶ Bloom filter helper function. Get the Bloom bits of a given value.
- Parameters
value (bytes) – Value to be encoded into the Bloom filter.
-
polyswarmclient.ethereum.offersclient
¶polyswarmclient.ethereum.relayclient
¶-
class
polyswarmclient.ethereum.relayclient.
RelayDepositTransaction
(client, amount)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.ethereum.relayclient.
RelayWithdrawTransaction
(client, amount)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
polyswarmclient.ethereum.stakingclient
¶-
class
polyswarmclient.ethereum.stakingclient.
StakeDepositTransaction
(client, amount)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.ethereum.stakingclient.
StakeWithdrawTransaction
(client, amount)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
polyswarmclient.ethereum.verifiers
¶-
class
polyswarmclient.ethereum.verifiers.
DecodedTransaction
(to, value, data, abi, signature, parameters)[source]¶ This is a decoded representation of the transaction object returned by polyswarmd.
-
classmethod
from_transaction
(cls, transaction, abi)[source]¶ Parse a transaction from data returned from polyswarmd.
- Parameters
transaction (dict) – Transaction to be simplified
abi (str, list[str]) – ABI of the expected function call
- Returns
If valid, returns a SimplifiedTransaction
- Return type
- Raises
ValueError – If invalid transaction is provided
-
classmethod
-
class
polyswarmclient.ethereum.verifiers.
AbstractTransactionVerifier
(parameters)[source]¶ Verifier is used to verify the details of a single transaction.
-
verify
(self, transaction)[source]¶ Called when a list of transactions were returned from polyswarmd. This function will verify the transactions, and determines if the transactions are expected.
- Parameters
transaction – Transaction representation returned from polyswarmd
- Returns
True if valid and expected
-
-
class
polyswarmclient.ethereum.verifiers.
NctApproveVerifier
(amount)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
NctTransferVerifier
(amount)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
PostBountyVerifier
(artifact_type, amount, artifact_uri, num_artifacts, duration, bloom, metadata)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
PostAssertionVerifier
(bounty_guid, bid, mask, commitment)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
RevealAssertionVerifier
(bounty_guid, index, nonce, verdicts, metadata)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
PostVoteVerifier
(bounty_guid, votes, valid_bloom)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
SettleBountyVerifier
(bounty_guid)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
-
class
polyswarmclient.ethereum.verifiers.
StakingDepositVerifier
(amount)[source]¶ Bases:
polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier
Package Contents¶
polyswarmclient.fast
¶
Submodules¶
polyswarmclient.fast.balanceclient
¶polyswarmclient.fast.bountiesclient
¶-
class
polyswarmclient.fast.bountiesclient.
PostBountyTransactionRequest
(client, guid, reward, artifact_uri, artifact_type, duration, metadata)[source]¶ Bases:
polyswarmclient.fast.transaction.PolySwarmTransactionRequest
-
class
polyswarmclient.fast.bountiesclient.
PostAssertionTransactionRequest
(client, bounty_guid, bid, verdict, metadata)[source]¶ Bases:
polyswarmclient.fast.transaction.PolySwarmTransactionRequest
-
class
polyswarmclient.fast.bountiesclient.
PostVoteTransactionRequest
(client, bounty_guid, vote)[source]¶ Bases:
polyswarmclient.fast.transaction.PolySwarmTransactionRequest
polyswarmclient.fast.offersclient
¶polyswarmclient.fast.relayclient
¶-
class
polyswarmclient.fast.relayclient.
RelayDepositTransaction
(client, amount)[source]¶ Bases:
polyswarmclient.ethereum.transaction.EthereumTransaction
-
class
polyswarmclient.fast.relayclient.
RelayWithdrawTransactionRequest
(client, amount)[source]¶ Bases:
polyswarmclient.fast.transaction.PolySwarmTransactionRequest
polyswarmclient.fast.stakingclient
¶polyswarmclient.fast.transaction
¶-
class
polyswarmclient.fast.transaction.
PolySwarmTransactionRequest
(client: Client, transaction: Transaction)[source]¶ Used to verify and post groups of transactions that make up a specific action.
For instance, when approving some funds to move, and calling a contract function that will consumer them.
Package Contents¶
polyswarmclient.filters
¶
Submodules¶
polyswarmclient.filters.bountyfilter
¶-
polyswarmclient.filters.bountyfilter.
split_filter
(ctx, param, value)[source]¶ -
Split some accept or exlcude arg from `key:value` to a tuple
- Parameters
ctx –
param –
value – list of exclude or accept values
- Returns
list[tuple] list of exclude|accept values as tuple key, value
-
class
polyswarmclient.filters.bountyfilter.
BountyFilter
(accept, reject)[source]¶ Bases:
polyswarmclient.filters.filter.MetadataFilter
Takes two objects list[Filter], accept and reject These dicts are used to filter metadata json blobs. Each filter runs against given metadata, and is used to determine if this participant will respond to a bounty
polyswarmclient.filters.confidencefilter
¶-
class
polyswarmclient.filters.confidencefilter.
ConfidenceModifier
(favor, penalize)[source]¶ Bases:
polyswarmclient.filters.filter.MetadataFilter
-
modify
(self, metadata, confidence)[source]¶ Check metadata against the penalty and favor filters. Matching both bonus and penalty results offset
- Parameters
metadata (any) – metadata dict to test
confidence (float) – confidence as returned by the Av engine
- Returns
confidence that is either more, same or less after comparing against bonus/penalty Filters
- Return type
(float)
-
polyswarmclient.filters.filter
¶-
polyswarmclient.filters.filter.
parse_filters
(ctx, param, value)[source]¶ -
Split some filters into a dict separated by type
- Parameters
ctx –
param –
value – list of 4 string tuples
- Returns
Dict where each key points to a list of Filters
- Return type
dict
-
class
polyswarmclient.filters.filter.
FilterComparison
[source]¶ Bases:
enum.Enum
Enum of supported metadata comparisons
-
class
polyswarmclient.filters.filter.
Filter
(key, comparison, target_value)[source]¶ Filter some metadata value
-
number_check
(self, value)[source]¶ Check a value as a number with GT, GTE, LT, or LTE comparisons
- Parameters
value (str|int|float|bytes) – Value to compare against
Returns: (bool) returns True if comparison matches
-
polyswarmclient.liveness
¶
Submodules¶
polyswarmclient.liveness.exceptions
¶polyswarmclient.liveness.liveness
¶-
class
polyswarmclient.liveness.liveness.
LivenessCheck
(loop_iteration_threshold=5, average_wait_threshold=10)[source]¶ Bases:
abc.ABC
polyswarmclient.liveness.local
¶-
class
polyswarmclient.liveness.local.
FileLock
(fileno)[source]¶ Locks a file so that only LivelinessRecorder or LivelinessChecker can access at any moment
-
class
polyswarmclient.liveness.local.
LocalLivenessCheck
(loop_iteration_threshold=5, average_wait_threshold=10)[source]¶ Bases:
polyswarmclient.liveness.liveness.LivenessCheck
Checks the liveness by reading a tempfile which should contain liveness information
-
class
polyswarmclient.liveness.local.
LocalLivenessRecorder
[source]¶ Bases:
polyswarmclient.liveness.liveness.LivenessRecorder
Record liveness data in a tempfile
polyswarmclient.producer
¶
Submodules¶
polyswarmclient.producer.base
¶polyswarmclient.producer.job
¶polyswarmclient.producer.jobprocessor
¶-
class
polyswarmclient.producer.jobprocessor.
PendingJob
(key: str, jobs: List[JobRequest], future: Future)[source]¶ A wrapper around a list of Jobs that are processing in the backend
-
__store_job_response
(self, response: JobResponse, confidence_modifier: Optional[ConfidenceModifier])[source]¶ Converts a JobResponse to ScanResult with modified confidence. Stores at the correct index in internal results
- Parameters
response – JobResponse to conver
confidence_modifier – an optional ConfidenceModifier to potentially change the confidence
- Returns
-
-
class
polyswarmclient.producer.jobprocessor.
JobProcessor
(redis: Redis, queue: str, confidence_modifier: Optional[ConfidenceModifier], period: float = 0.25, redis_error_callback: Optional[Callable[[], Coroutine]] = None)[source]¶ Keeps track pending jobs, and polls the PendingJob results every period of time (.5 seconds)
Package Contents¶
-
class
polyswarmclient.producer.
Producer
(client, redis_uri, queue, time_to_post, bounty_filter=None, confidence_modifier=None, rate_limit=None)[source]¶
-
class
polyswarmclient.producer.
JobRequest
[source]¶ -
polyswarmd_uri
:str¶
-
guid
:str¶
-
index
:int¶
-
uri
:str¶
-
artifact_type
:int¶
-
duration
:int¶
-
metadata
:Optional[Dict[str, Any]]¶
-
chain
:str¶
-
ts
:int¶
-
key
¶
-
is_expired
(self, now=None)¶
-
get_artifact_type
(self)¶
-
asdict
(self)¶
-
-
class
polyswarmclient.producer.
JobResponse
[source]¶ -
index
:int¶
-
bit
:bool¶
-
verdict
:bool¶
-
confidence
:float¶
-
metadata
:str¶
-
asdict
(self)¶
-
-
class
polyswarmclient.producer.
JobProcessor
(redis: Redis, queue: str, confidence_modifier: Optional[ConfidenceModifier], period: float = 0.25, redis_error_callback: Optional[Callable[[], Coroutine]] = None)[source]¶ Keeps track pending jobs, and polls the PendingJob results every period of time (.5 seconds)
-
redis_uri
:str¶
-
confidence_modifier
:Optional[ConfidenceModifier]¶
-
queue
:str¶
-
period
:float¶
-
pending_jobs
:Dict[str, PendingJob]¶
-
job_lock
:Optional[asyncio.Lock]¶
-
redis
:Optional[Redis]¶
-
task
¶
-
reset_callback
¶
-
stop
(self)¶ Stop processing jobs
-
-
class
polyswarmclient.producer.
PendingJob
(key: str, jobs: List[JobRequest], future: Future)[source]¶ A wrapper around a list of Jobs that are processing in the backend
-
key
:str¶
-
jobs
:List[JobRequest]¶
-
results
:Dict[int, ScanResult]¶
-
future
:Future¶
-
times
(self)¶
-
time_ratios
(self)¶
-
__store_job_response
(self, response: JobResponse, confidence_modifier: Optional[ConfidenceModifier])¶ Converts a JobResponse to ScanResult with modified confidence. Stores at the correct index in internal results
- Parameters
response – JobResponse to conver
confidence_modifier – an optional ConfidenceModifier to potentially change the confidence
- Returns
-
is_done
(self)¶ Checks all things to see if it is done :return: true if expired, or has all results
-
__is_expired
(self)¶ Returns true if any of the jobs are expired
-
__has_all_results
(self)¶ Returns true if all the jobs have a result
-
__finish
(self)¶ Set the results in the future and mark done
-
polyswarmclient.ratelimit
¶
Submodules¶
polyswarmclient.ratelimit.abstractratelimit
¶polyswarmclient.ratelimit.redis
¶-
class
polyswarmclient.ratelimit.redis.
RedisRateLimit
(redis, queue, limit, key_manager=None)[source]¶ Bases:
polyswarmclient.ratelimit.abstractratelimit.AbstractRateLimit
Third Party limitation where redis is used to track a daily scan limit. Keys are based on the current date, and will expire the next day.
This implementation is used in the producer and worker since they use Redis already.
Submodules¶
polyswarmclient.abstractambassador
¶
Module Contents¶
-
class
polyswarmclient.abstractambassador.
QueuedBounty
(artifact_type, amount, ipfs_uri, duration, api_key=None, metadata=None)[source]¶ Bases:
object
-
class
polyswarmclient.abstractambassador.
AbstractAmbassador
(client, testing=0, chains=None, watchdog=0, submission_rate=0)[source]¶ Bases:
abc.ABC
-
classmethod
connect
(cls, polyswarmd_addr, keyfile, password, api_key=None, testing=0, chains=None, watchdog=0, submission_rate=0)[source]¶ Connect the Ambassador to a Client.
- Parameters
polyswarmd_addr (str) – URL of polyswarmd you are referring to.
keyfile (str) – Keyfile filename.
password (str) – Password associated with Keyfile.
api_key (str) – Your PolySwarm API key.
testing (int) – Number of testing bounties to use.
chains (set(str)) – Set of chains you are acting on.
- Returns
Ambassador instantiated with a Client.
- Return type
-
classmethod
polyswarmclient.abstractarbiter
¶
Module Contents¶
-
class
polyswarmclient.abstractarbiter.
AbstractArbiter
(client, testing=0, scanner=None, chains=None, artifact_types=None)[source]¶ Bases:
object
-
classmethod
connect
(cls, polyswarmd_addr, keyfile, password, api_key=None, testing=0, scanner=None, chains=None, artifact_types=None)[source]¶ Connect the Arbiter to a Client.
- Parameters
polyswarmd_addr (str) – URL of polyswarmd you are referring to.
keyfile (str) – Keyfile filename.
password (str) – Password associated with Keyfile.
api_key (str) – Your PolySwarm API key.
testing (int) – Number of testing bounties to use.
scanner (AbstractScanner) – Scanner for scanning artifacts
chains (set(str)) – Set of chains you are acting on.
artifact_types (list(ArtifactType)) – List of artifact types you support
- Returns
Arbiter instantiated with a Client.
- Return type
-
classmethod
polyswarmclient.abstractmicroengine
¶
Module Contents¶
-
class
polyswarmclient.abstractmicroengine.
AbstractMicroengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, bid_strategy=None, bounty_filter=BountyFilter(None, None), confidence_modifier=ConfidenceModifier(None, None))[source]¶ Bases:
object
-
classmethod
connect
(cls, polyswarmd_addr, keyfile, password, api_key=None, testing=0, scanner=None, chains=None, artifact_types=None, bid_strategy=None, bounty_filter=BountyFilter(None, None), confidence_modifier=ConfidenceModifier(None, None))[source]¶ Connect the Microengine to a Client.
- Parameters
polyswarmd_addr (str) – URL of polyswarmd you are referring to.
keyfile (str) – Keyfile filename.
password (str) – Password associated with Keyfile.
api_key (str) – Your PolySwarm API key.
testing (int) – Number of testing bounties to use.
scanner (Scanner) – Scanner instance to use.
chains (set(str)) – Set of chains you are acting on.
artifact_types (list(ArtifactType)) – List of artifact types you support
bid_strategy (BidStrategyBase) – Bid Strategy for bounties
bounty_filter (BountyFilter) – Filters to accept/reject artifacts
confidence_modifier (ConfidenceModifier) – Filters to adjust confidence based on metadata
- Returns
Microengine instantiated with a Client.
- Return type
-
classmethod
polyswarmclient.abstractscanner
¶
Module Contents¶
-
class
polyswarmclient.abstractscanner.
ScanResult
(bit=False, verdict=False, confidence=1.0, metadata=Verdict().set_malware_family('').json())[source]¶ Bases:
object
Results from scanning one artifact
-
class
polyswarmclient.abstractscanner.
ScanMode
[source]¶ Bases:
enum.Enum
Denote whether the Scanner is using asynchronous or synchronous scan
-
class
polyswarmclient.abstractscanner.
AbstractScanner
(mode: ScanMode = ScanMode.ASYNC)[source]¶ Base Scanner class. To be overwritten with other scanning logic.
This class offers two scan options, which can be specified by passing a ScanMode enum value as mode. It uses asynchronous scan by default.
The function scan_async is a coroutine function where everything called from this function must be async compatible, That means it uses only non-blocking IO, and runs nothing cpu-bound, like hash functions.
The function scan_sync is a synchronous function where anything goes. It is called in a ThreadPoolExecutor so it is compatible with the worker that uses asyncio.
Overwriting scan directly is deprecated.
-
scan_sync
(self, guid, artifact_type, content, metadata, chain)[source]¶ Override this to implement custom synchronous scanning logic
- Parameters
guid (str) – GUID of the bounty under analysis, use to track artifacts in the same bounty
artifact_type (ArtifactType) – Artifact type for the bounty being scanned
content (bytes) – Content of the artifact to scan
metadata (dict) – Metadata dict from the ambassador
chain (str) – What chain are we operating on
- Returns
Result of this scan
- Return type
-
polyswarmclient.backoff_wrapper
¶
Module Contents¶
-
class
polyswarmclient.backoff_wrapper.
BackoffWrapper
(func, **kwargs)[source]¶ Uses a generator to create backoff times
This is for use in functions that don’t return. In our use case, listen_for_events is not supposed to return, but exists as a long running Task. Using the decorator, the backoff time grows forever, because the function is only called one time. So each error causes a longer and longer timeout.
This adds an ability to reset the backoff, so your long running function can reduce the timeout after success
polyswarmclient.bidstrategy
¶
Module Contents¶
polyswarmclient.config
¶
Module Contents¶
-
polyswarmclient.config.
validate_apikey
(ctx, param, value)[source]¶ -
Validates the API key passed in through click parameters
polyswarmclient.corpus
¶
Module Contents¶
polyswarmclient.events
¶
Module Contents¶
-
class
polyswarmclient.events.
Callback
[source]¶ Bases:
object
Abstract callback class which is the parent to a number of child callback classes to be used in different scenarios.
Note
Classes which extend Callback are expected to impliment the run method.
-
class
polyswarmclient.events.
OnRunCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon entering the event loop for the first time, use for initialization
-
class
polyswarmclient.events.
OnStopCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called when the client is stopping
This can happen on errors, or due to a signal
-
class
polyswarmclient.events.
OnNewBlockCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon receiving a new block, scheduled events triggered separately
-
class
polyswarmclient.events.
OnNewBountyCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon receiving a new bounty
-
class
polyswarmclient.events.
OnNewAssertionCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon receiving a new assertion
-
class
polyswarmclient.events.
OnRevealAssertionCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon receiving a new assertion reveal
-
class
polyswarmclient.events.
OnNewVoteCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon receiving a new arbiter vote
-
class
polyswarmclient.events.
OnQuorumReachedCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon a bounty reaching quorum
-
class
polyswarmclient.events.
OnSettledBountyCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon a bounty being settled
-
class
polyswarmclient.events.
OnDeprecatedCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon the BountyRegistry contract being deprecated
-
class
polyswarmclient.events.
OnInitializedChannelCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called upon a channel being initialized
-
class
polyswarmclient.events.
Schedule
[source]¶ Bases:
object
Generic Schedule class. Uses a PriorityQueue data structure to store Events.
-
empty
(self)[source]¶ Return True if the queue is empty.
- Returns
Is the queue empty.
- Return type
boolean
-
peek
(self)[source]¶ Return True if the queue is empty.
- Returns
Tuple at the front of the queue if the queue is full, else None.
- Return type
(block, event)
-
-
class
polyswarmclient.events.
Event
(guid)[source]¶ Bases:
object
Generic Event class. Stores GUID and can compare for equality and order Events.
- Parameters
guid (str, None) – GUID of the event.
-
class
polyswarmclient.events.
RevealAssertion
(guid, index, nonce, verdicts, metadata)[source]¶ Bases:
polyswarmclient.events.Event
An assertion scheduled to be publically revealed
- Parameters
guid (str) – GUID of the bounty being asserted on
index (int) – Index of the assertion to reveal
nonce (str) – Secret nonce used to reveal assertion
verdicts (List[bool]) – List of verdicts for each artifact in the bounty
metadata (str) – Optional metadata
-
class
polyswarmclient.events.
OnRevealAssertionDueCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called when an assertion is needing to be revealed
-
class
polyswarmclient.events.
VoteOnBounty
(guid, votes, valid_bloom)[source]¶ Bases:
polyswarmclient.events.Event
A scheduled vote from an arbiter :param guid: GUID of the bounty being voted on :type guid: str :param votes: List of votes for each artifact in the bounty :type votes: List[bool] :param valid_bloom: Is the bloom filter submitted with the bounty valid :type valid_bloom: bool
-
class
polyswarmclient.events.
OnVoteOnBountyDueCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called when a bounty is needing to be voted on
-
class
polyswarmclient.events.
SettleBounty
(guid)[source]¶ Bases:
polyswarmclient.events.Event
A bounty scheduled to be settled :param guid: GUID of the bounty being asserted on :type guid: str
-
class
polyswarmclient.events.
OnSettleBountyDueCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called when a bounty is needing to be settled
-
class
polyswarmclient.events.
WithdrawStake
(amount)[source]¶ Bases:
polyswarmclient.events.Event
A scheduled stake withdrawal from an arbiter
- Parameters
amount (int) – Amount to withdraw from stake
-
class
polyswarmclient.events.
OnWithdrawStakeDueCallback
[source]¶ Bases:
polyswarmclient.events.Callback
Called when a an arbiter needs to withdraw stake (due to deprecation)
polyswarmclient.exceptions
¶
Module Contents¶
-
exception
polyswarmclient.exceptions.
PolyswarmClientException
[source]¶ Bases:
Exception
polyswarm-client related errors
-
exception
polyswarmclient.exceptions.
ApiKeyException
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Used an API key when not communicating over https, without explicitly allowing
-
exception
polyswarmclient.exceptions.
InvalidBidError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Fault in bid logic that resulted in a bid that is not between the min and max values provided by polyswarmd
-
exception
polyswarmclient.exceptions.
LowBalanceError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Not enough NCT to complete the requested action
-
exception
polyswarmclient.exceptions.
TransactionError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
A transaction failed
-
exception
polyswarmclient.exceptions.
InvalidMetadataError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Metadata does not match the valid schema
-
exception
polyswarmclient.exceptions.
RateLimitedError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Hit the rate limit from polyswarmd
-
exception
polyswarmclient.exceptions.
NonceDesyncError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Got a nonce too low or too high error
-
exception
polyswarmclient.exceptions.
ReceiptError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Failed to get receipt from polyswarmd
-
exception
polyswarmclient.exceptions.
UnsupportedHashError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Raised when a hash doesn’t match the format of a hash we use
-
exception
polyswarmclient.exceptions.
ScannerSetupFailedError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Scanner reported an unsuccessful setup
polyswarmclient.log_formatter
¶
Module Contents¶
-
class
polyswarmclient.log_formatter.
ExtraTextFormatter
[source]¶ Bases:
logging.Formatter
Custom formatter that adds extra fields to the message string
-
format
(self, record)[source]¶ Takes a LogRecord and sets record.message = record.msg % record.args This one does some extra work. It searches the record dict for some extra keys we use in the client. (specified as extra= in the logger statement) If it finds one, it grabs the dict and adds an extra %s arg to record.msg, and the dict value to the record.args tuple.
-
-
class
polyswarmclient.log_formatter.
JSONFormatter
[source]¶ Bases:
pythonjsonlogger.jsonlogger.JsonFormatter
Class to add custom JSON fields to our logger. Presently just adds a timestamp if one isn’t present and the log level. INFO: https://github.com/madzak/python-json-logger#customizing-fields
polyswarmclient.parameters
¶
Module Contents¶
polyswarmclient.request_rate_limit
¶
Module Contents¶
polyswarmclient.utils
¶
Module Contents¶
-
polyswarmclient.utils.
DEPRECATION_MESSAGE
= polyswarm-client 2.x.x is deprecated. However, polyswarm-client 2.x.x will still work with some PolySwarm communities in the near term.[source]¶ Action is required to continue using 2.x.x.
If your build is based off the polyswarm-client:latest docker image, you MUST change to another tag. Tag :2 will include all future fixes for polyswarm-client 2.x.x.
-
polyswarmclient.utils.
asyncio_join
()[source]¶ -
Gather all remaining tasks, assumes loop is not running
-
polyswarmclient.utils.
check_response
(response)[source]¶ -
Check the status of responses from polyswarmd
- Parameters
response – Response dict parsed from JSON from polyswarmd
- Returns
True if successful else False
- Return type
(bool)
-
polyswarmclient.utils.
is_valid_sha256
(uri)[source]¶ -
Ensure that a given uri is a valid sha256 hash by checking length, and converting to an int
- Parameters
uri (str) – uri to validate
- Returns
is this valid
- Return type
bool
-
polyswarmclient.utils.
is_valid_ipfs_uri
(ipfs_uri)[source]¶ -
Ensure that a given ipfs_uri is valid by checking length and base58 encoding.
- Parameters
ipfs_uri (str) – ipfs_uri to validate
- Returns
is this valid?
- Return type
bool
-
class
polyswarmclient.utils.
AsyncArtifactTempfile
(blob: 'bytes' = None, filename: 'str' = None, mode: 'str' = 'w+b')[source]¶ asynchronous ctxmgr for temporary artifacts
Notes:
The following underlying file’s methods are awaited:
flush, peek, read, seek, write
You can use the object like an ordinary context manager or supply the binary blob to be written as the first argument
>>> blob = b'hello world' >>> async with AsyncArtifactTempfile(blob) as f: >>> with open(f.name, 'rb') as of: >>> of.read() b'hello world' >>> async with AsyncArtifactTempfile() as f: >>> await f.write(blob) >>> await f.read() b'hello world'
The underlying file is always deleted after ctxmgr exits
Package Contents¶
-
class
polyswarmclient.
NonceManager
(client, chain)¶ Manages the nonce for some Ethereum chain
-
static
find_gaps
(nonces)¶ Finds any gaps between base nonce and the last nonce in the given nonces list.
- Parameters
nonces (list[int]) – list of nonces being checked
- Returns
(list[int]): Any missing nonces between base_nonce and the last given nonce
-
static
-
exception
polyswarmclient.
RateLimitedError
[source]¶ Bases:
polyswarmclient.exceptions.PolyswarmClientException
Hit the rate limit from polyswarmd
-
class
polyswarmclient.
LocalLivenessRecorder
[source]¶ Bases:
polyswarmclient.liveness.liveness.LivenessRecorder
Record liveness data in a tempfile
-
write_sync
(self, content)¶ Write the given content to the file at the given path.
- Parameters
content – content to write into the file
-
-
class
polyswarmclient.
BackoffWrapper
(func, **kwargs)[source]¶ Uses a generator to create backoff times
This is for use in functions that don’t return. In our use case, listen_for_events is not supposed to return, but exists as a long running Task. Using the decorator, the backoff time grows forever, because the function is only called one time. So each error causes a longer and longer timeout.
This adds an ability to reset the backoff, so your long running function can reduce the timeout after success
-
reset
(self)¶
-
-
class
polyswarmclient.
Client
(polyswarmd_addr, keyfile, password, api_key=None, tx_error_fatal=False)[source]¶ Bases:
object
Client to connected to a Ethereum wallet as well as a polyswarmd instance.
- Parameters
polyswarmd_addr (str) – URI of polyswarmd you are referring to.
keyfile (str) – Keyfile filename.
password (str) – Password associated with keyfile.
api_key (str) – Your PolySwarm API key.
tx_error_fatal (bool) – Transaction errors are fatal and exit the program
insecure_transport (bool) – Allow insecure transport such as HTTP?
liveness
¶
Submodules¶
liveness.__main__
¶
Module Contents¶
microengine
¶
Subpackages¶
microengine.bidstrategy
¶
Submodules¶
microengine.bidstrategy.aggressive
¶microengine.bidstrategy.conservative
¶microengine.bidstrategy.default
¶Submodules¶
microengine.__main__
¶
Module Contents¶
-
microengine.__main__.
choose_backend
(backend)[source]¶ -
Resolves microengine name string to implementation
- Parameters
backend (str) – Name of the backend to load, either one of the predefined implementations or the name of a module to load (module:ClassName syntax or default of module:Microengine)
- Returns
Microengine class of the selected implementation
- Return type
(Class)
- Raises
(Exception) – If backend is not found
-
microengine.__main__.
choose_bid_strategy
(bid_strategy)[source]¶ -
Resolves bid strategy name string to implementation
- Parameters
bid_strategy (str) – Name of the bid strategy to load, either one of the predefined implementations or the name of a module to load (module:ClassName syntax or default of )
- Returns
Microengine class of the selected implementation
- Return type
(Class)
- Raises
(Exception) – If backend is not found
microengine.clamav
¶
Module Contents¶
-
class
microengine.clamav.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
Microengine which scans samples through clamd.
- Parameters
client (Client) – Client to use
testing (int) – How many test bounties to respond to
chains (set[str]) – Chain(s) to operate on
microengine.eicar
¶
Module Contents¶
-
class
microengine.eicar.
Scanner
[source]¶ Bases:
polyswarmclient.abstractscanner.AbstractScanner
-
scan_sync
(self, guid, artifact_type, content, metadata, chain)[source]¶ Scan an artifact
- Parameters
guid (str) – GUID of the bounty under analysis, use to track artifacts in the same bounty
artifact_type (ArtifactType) – Artifact type for the bounty being scanned
content (bytes) – Content of the artifact to be scan
metadata (dict) –
chain (str) – Chain we are operating on
- Returns
Result of this scan
- Return type
-
-
class
microengine.eicar.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
Microengine which tests for the EICAR test file.
- Parameters
client (Client) – Client to use
testing (int) – How many test bounties to respond to
chains (set[str]) – Chain(s) to operate on
microengine.multi
¶
Module Contents¶
-
class
microengine.multi.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
Microengine which aggregates multiple sub-microengines
microengine.producer
¶
Module Contents¶
-
class
microengine.producer.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, bid_strategy=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
microengine.scratch
¶
Module Contents¶
-
class
microengine.scratch.
Scanner
[source]¶ Bases:
polyswarmclient.abstractscanner.AbstractScanner
-
scan_sync
(self, guid, artifact_type, content, metadata, chain)[source]¶ Scan an artifact
- Parameters
guid (str) – GUID of the bounty under analysis, use to track artifacts in the same bounty
artifact_type (ArtifactType) – Artifact type for the bounty being scanned
content (bytes) – Content of the artifact to be scan
metadata (dict) –
chain (str) – Chain we are operating on
- Returns
Result of this scan
- Return type
-
-
class
microengine.scratch.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
Scratch microengine is the same as the default behavior.
- Parameters
client (Client) – Client to use
testing (int) – How many test bounties to respond to
chains (set[str]) – Chain(s) to operate on
microengine.yara
¶
Module Contents¶
-
class
microengine.yara.
Scanner
[source]¶ Bases:
polyswarmclient.abstractscanner.AbstractScanner
-
scan_sync
(self, guid, artifact_type, content, metadata, chain)[source]¶ Scan an artifact with Yara.
- Parameters
guid (str) – GUID of the bounty under analysis, use to track artifacts in the same bounty
artifact_type (ArtifactType) – Artifact type for the bounty being scanned
content (bytes) – Content of the artifact to be scan
metadata (dict) –
chain (str) – Chain we are operating on
- Returns
Result of this scan
- Return type
-
-
class
microengine.yara.
Microengine
(client, testing=0, scanner=None, chains=None, artifact_types=None, **kwargs)[source]¶ Bases:
polyswarmclient.abstractmicroengine.AbstractMicroengine
Microengine which matches samples against yara rules
- 1
Created with sphinx-autoapi
polyswarm-client
is a convenient library on which to build PolySwarm market participants.
Here you’ll find auto-generated documentation based on the polyswarm-client
source code.
Consulting these low level details is unnecessary for developing a successful PolySwarm participant. Most users will instead want to consult the PolySwarm Documentation.
Developers interested in low level polyswarm-client
details can do so by navigating to “API Reference” on the left.