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__.logger[source]
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.__main__.main(log, client_log, polyswarmd_addr, keyfile, password, api_key, backend, testing, insecure_transport, allow_key_over_http, chains, watchdog, log_format, submission_rate)[source]
Entrypoint for the ambassador driver
ambassador.eicar
Module Contents
ambassador.eicar.logger[source]
ambassador.eicar.EICAR[source]
ambassador.eicar.NOT_EICAR = not a malicious file[source]
ambassador.eicar.ARTIFACTS = [None, None][source]
ambassador.eicar.BOUNTY_TEST_DURATION_BLOCKS[source]
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
ambassador.filesystem.logger[source]
ambassador.filesystem.ARTIFACT_DIRECTORY[source]
ambassador.filesystem.ARTIFACT_BLACKLIST[source]
ambassador.filesystem.ARTIFACTS_PER_BOUNTY[source]
ambassador.filesystem.BOUNTY_TEST_DURATION_BLOCKS[source]
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__.logger[source]
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.__main__.main(log, client_log, redis_addr, queue, backend, tasks, download_limit, scan_limit, api_key, testing, log_format, scan_time_requirement, daily_rate_limit, hourly_rate_limit, minutely_rate_limit, secondly_rate_limit, allow_key_over_http)[source]
Entrypoint for the worker driver
worker.base
Module Contents
worker.base.logger[source]
worker.base.REQUEST_TIMEOUT = 5.0[source]
class worker.base.RateLimitAggregate(redis, queue, daily_rate_limit, hourly_rate_limit, minutely_rate_limit, secondly_rate_limit)[source]

Bases: polyswarmclient.ratelimit.abstractratelimit.AbstractRateLimit

daily :Optional[RedisRateLimit][source]
hourly :Optional[RedisRateLimit][source]
minutely :Optional[RedisRateLimit][source]
secondly :Optional[RedisRateLimit][source]
class worker.base.OptionalSemaphore(value=1, loop=None)[source]

Bases: asyncio.Semaphore

given_value :int[source]
release(self)[source]
class worker.base.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)[source]
start(self, loop: asyncio.AbstractEventLoop)[source]
setup_synchronization(self, loop: asyncio.AbstractEventLoop)[source]
setup_graceful_shutdown(self, loop: asyncio.AbstractEventLoop)[source]
handle_signal(self)[source]
get_remaining_time(self, job: JobRequest)[source]
rate_limit_respond(self, job: JobRequest)[source]
is_key_secure(self, job: JobRequest)[source]
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__.logger[source]
balancemanager.__main__.validate_optional_transfer_amount(ctx, param, value)[source]
balancemanager.__main__.validate_transfer_amount(ctx, param, value)[source]
balancemanager.__main__.polyswarm_client(func)[source]
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
balancemanager.__main__.view_balance(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, chain)[source]
balancemanager.__main__.view_stake(polyswarmd_addr, keyfile, password, api_key, testing, insecure_transport, allow_key_over_http, denomination, chain)[source]

Package Contents

balancemanager.logger[source]
balancemanager.RELAY_LEEWAY = 5[source]
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.

run(self)[source]

Starts the client on whichever chain this uses.

run_oneshot(self)[source]

Runs run_task once

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.

run(self)[source]

Starts the client. Have to run with both chains, or lots of nonce errors

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.

run(self)[source]

Starts the client on whichever chain this uses.

run_oneshot(self)[source]

Runs run_task once

class balancemanager.ViewStake[source]

Bases: balancemanager.ViewBalance

arbiter

Subpackages

arbiter.verbatimdb
Submodules
arbiter.verbatimdb.__main__
Module Contents
arbiter.verbatimdb.__main__.main(malicious, benign, output, log_format)[source]
arbiter.verbatimdb.db
Module Contents
arbiter.verbatimdb.db.generate_db(db_file, malicious_dir, benign_dir)[source]
arbiter.verbatimdb.db.insert(cursor, path, result)[source]

Submodules

arbiter.__main__
Module Contents
arbiter.__main__.logger[source]
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.__main__.main(log, client_log, polyswarmd_addr, keyfile, password, api_key, backend, testing, insecure_transport, allow_key_over_http, chains, log_format, artifact_type)[source]
Entrypoint for the arbiter driver
arbiter.clamav
Module Contents
arbiter.clamav.logger[source]
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
arbiter.eicar.logger[source]
arbiter.eicar.EICAR[source]
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.producer.logger[source]
arbiter.producer.REDIS_ADDR[source]
arbiter.producer.QUEUE[source]
arbiter.producer.RATE_LIMIT[source]
arbiter.producer.TIME_TO_POST_VOTE = 6[source]
class arbiter.producer.Arbiter(client, testing=0, scanner=None, chains=None, artifact_types=None)[source]

Bases: polyswarmclient.abstractarbiter.AbstractArbiter

arbiter.verbatim
Module Contents
arbiter.verbatim.logger[source]
arbiter.verbatim.ARTIFACT_DIRECTORY[source]
arbiter.verbatim.EICAR[source]
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
Submodules
polyswarmclient.ethereum.bountiesclient.base
Module Contents
polyswarmclient.ethereum.bountiesclient.base.logger[source]
class polyswarmclient.ethereum.bountiesclient.base.BountiesClient(client)[source]

Bases: object

polyswarmclient.ethereum.bountiesclient.transaction
Module Contents
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

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.bountiesclient.transaction.PostAssertionTransaction(client, bounty_guid, bid, assertion_fee, mask, commitment)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_body(self)[source]
get_path(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.bountiesclient.transaction.RevealAssertionTransaction(client, bounty_guid, index, nonce, verdicts, metadata)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.bountiesclient.transaction.PostVoteTransaction(client, bounty_guid, votes, valid_bloom)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.bountiesclient.transaction.SettleBountyTransaction(client, bounty_guid)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
polyswarmclient.ethereum.transaction
Submodules
polyswarmclient.ethereum.transaction.base
Module Contents
polyswarmclient.ethereum.transaction.base.logger[source]
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

get_path(self)[source]

Get the path of the route to build this transaction

Returns

Polyswarmd path to get the transaction data

Return type

str

get_body(self)[source]

Build the payload to send to polyswarmd :returns: Dict payload

verify(self, transactions)[source]

Check the given transactions against known expectations

Parameters

transactions (list) –

Returns

True if transactions match expectations. False otherwise

Return type

(bool)

polyswarmclient.ethereum.transaction.noncemanager
Module Contents
polyswarmclient.ethereum.transaction.noncemanager.logger[source]
class polyswarmclient.ethereum.transaction.noncemanager.NonceManager(client, chain)[source]

Manages the nonce for some Ethereum chain

static find_gaps(nonces)[source]

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

Package Contents
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

Submodules
polyswarmclient.ethereum.balanceclient
Module Contents
polyswarmclient.ethereum.balanceclient.logger[source]
polyswarmclient.ethereum.balanceclient.MAX_TRIES[source]
class polyswarmclient.ethereum.balanceclient.BalanceClient(client)[source]

Bases: object

polyswarmclient.ethereum.bloom
Module Contents
polyswarmclient.ethereum.bloom.FILTER_BITS[source]
polyswarmclient.ethereum.bloom.HASH_FUNCS = 8[source]
polyswarmclient.ethereum.bloom.logger[source]
class polyswarmclient.ethereum.bloom.BloomFilter(value=0)[source]

Bases: numbers.Number

value[source]
__int__(self)[source]
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

BloomFilter

__contains__(self, value)[source]
__index__(self)[source]
_combine(self, other)[source]
__or__(self, other)[source]
__add__(self, other)[source]
_icombine(self, other)[source]
__ior__(self, other)[source]
__iadd__(self, other)[source]
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.

static get_chunks_for_bloom(value_hash)[source]

Bloom filter helper function. Turn a value hash into a series of chunks.

Parameters

value_hash (bytes) – Hash of to be encoded into the Bloom filter.

Yields

chunk (bytes) – Chunks of the value hash.

static chunk_to_bloom_bits(chunk)[source]

Bloom filter helper function. Turn a chunk into a series of actual bytes.

Parameters

chunk (bytes) – Byte encoded chunk.

polyswarmclient.ethereum.offersclient
Module Contents
polyswarmclient.ethereum.offersclient.logger[source]
class polyswarmclient.ethereum.offersclient.OffersClient(client)[source]

Bases: object

OffersClient to handle offers. Presently stores a given client and parameters.

polyswarmclient.ethereum.relayclient
Module Contents
polyswarmclient.ethereum.relayclient.logger[source]
class polyswarmclient.ethereum.relayclient.RelayDepositTransaction(client, amount)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.relayclient.RelayWithdrawTransaction(client, amount)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.relayclient.RelayClient(client)[source]

Bases: object

polyswarmclient.ethereum.stakingclient
Module Contents
polyswarmclient.ethereum.stakingclient.logger[source]
class polyswarmclient.ethereum.stakingclient.StakeDepositTransaction(client, amount)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.stakingclient.StakeWithdrawTransaction(client, amount)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.ethereum.stakingclient.StakingClient(client)[source]

Bases: object

polyswarmclient.ethereum.verifiers
Module Contents
polyswarmclient.ethereum.verifiers.logger[source]
polyswarmclient.ethereum.verifiers.UNKNOWN_PARAMETER = XXX[source]
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

DecodedTransaction

Raises

ValueError – If invalid transaction is provided

__repr__(self)[source]
class polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier(parameters)[source]

Verifier is used to verify the details of a single transaction.

ABI = ['', []][source]
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

__repr__(self)[source]
class polyswarmclient.ethereum.verifiers.NctApproveVerifier(amount)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['approve', ['address', 'uint256']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.NctTransferVerifier(amount)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['transfer', ['address', 'uint256']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.PostBountyVerifier(artifact_type, amount, artifact_uri, num_artifacts, duration, bloom, metadata)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['postBounty', ['uint128', 'uint256', 'uint256', 'string', 'uint256', 'uint256', 'uint256[8]', 'string']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.PostAssertionVerifier(bounty_guid, bid, mask, commitment)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['postAssertion', ['uint128', 'uint256[]', 'uint256', 'uint256']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.RevealAssertionVerifier(bounty_guid, index, nonce, verdicts, metadata)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['revealAssertion', ['uint128', 'uint256', 'uint256', 'uint256', 'string']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.PostVoteVerifier(bounty_guid, votes, valid_bloom)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['voteOnBounty', ['uint128', 'uint256', 'bool']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.SettleBountyVerifier(bounty_guid)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['settleBounty', ['uint128']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.StakingDepositVerifier(amount)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['deposit', ['uint256']][source]
verify(self, transaction)[source]
class polyswarmclient.ethereum.verifiers.StakingWithdrawVerifier(amount)[source]

Bases: polyswarmclient.ethereum.verifiers.AbstractTransactionVerifier

ABI = ['withdraw', ['uint256']][source]
verify(self, transaction)[source]
Package Contents
class polyswarmclient.ethereum.BalanceClient(client)[source]

Bases: object

class polyswarmclient.ethereum.BountiesClient(client)[source]

Bases: object

class polyswarmclient.ethereum.OffersClient(client)[source]

Bases: object

OffersClient to handle offers. Presently stores a given client and parameters.

class polyswarmclient.ethereum.RelayClient(client)[source]

Bases: object

class polyswarmclient.ethereum.StakingClient(client)[source]

Bases: object

polyswarmclient.fast
Submodules
polyswarmclient.fast.balanceclient
Module Contents
polyswarmclient.fast.balanceclient.logger[source]
polyswarmclient.fast.balanceclient.MAX_TRIES[source]
polyswarmclient.fast.balanceclient.TTL[source]
polyswarmclient.fast.balanceclient.MAX_SIZE = 20[source]
class polyswarmclient.fast.balanceclient.BalanceClient(client)[source]

Bases: object

polyswarmclient.fast.bountiesclient
Module Contents
polyswarmclient.fast.bountiesclient.logger[source]
polyswarmclient.fast.bountiesclient.DEFAULT_METADATA = {"malware_family": ""}[source]
class polyswarmclient.fast.bountiesclient.PostBountyTransactionRequest(client, guid, reward, artifact_uri, artifact_type, duration, metadata)[source]

Bases: polyswarmclient.fast.transaction.PolySwarmTransactionRequest

path[source]
class polyswarmclient.fast.bountiesclient.PostAssertionTransactionRequest(client, bounty_guid, bid, verdict, metadata)[source]

Bases: polyswarmclient.fast.transaction.PolySwarmTransactionRequest

path[source]
class polyswarmclient.fast.bountiesclient.PostVoteTransactionRequest(client, bounty_guid, vote)[source]

Bases: polyswarmclient.fast.transaction.PolySwarmTransactionRequest

path[source]
class polyswarmclient.fast.bountiesclient.BountiesClient(client)[source]

Bases: object

polyswarmclient.fast.offersclient
Module Contents
polyswarmclient.fast.offersclient.logger[source]
class polyswarmclient.fast.offersclient.OffersClient(client)[source]

Bases: object

OffersClient to handle offers. Presently stores a given client and parameters.

polyswarmclient.fast.relayclient
Module Contents
polyswarmclient.fast.relayclient.logger[source]
class polyswarmclient.fast.relayclient.RelayDepositTransaction(client, amount)[source]

Bases: polyswarmclient.ethereum.transaction.EthereumTransaction

get_path(self)[source]
get_body(self)[source]
has_required_event(self, transaction_events)[source]
class polyswarmclient.fast.relayclient.RelayWithdrawTransactionRequest(client, amount)[source]

Bases: polyswarmclient.fast.transaction.PolySwarmTransactionRequest

path[source]
class polyswarmclient.fast.relayclient.RelayClient(client)[source]

Bases: object

polyswarmclient.fast.stakingclient
Module Contents
polyswarmclient.fast.stakingclient.logger[source]
class polyswarmclient.fast.stakingclient.StakingClient(client)[source]

Bases: object

polyswarmclient.fast.transaction
Module Contents
polyswarmclient.fast.transaction.logger[source]
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.

path[source]

Get the path of the route to build this transaction

Returns

Polyswarmd path to get the transaction data

Return type

str

sign_transaction(self)[source]

Signs a transaction

Returns

SignedTransaction

Package Contents
class polyswarmclient.fast.BalanceClient(client)[source]

Bases: object

class polyswarmclient.fast.BountiesClient(client)[source]

Bases: object

class polyswarmclient.fast.OffersClient(client)[source]

Bases: object

OffersClient to handle offers. Presently stores a given client and parameters.

class polyswarmclient.fast.RelayClient(client)[source]

Bases: object

class polyswarmclient.fast.StakingClient(client)[source]

Bases: object

polyswarmclient.filters
Submodules
polyswarmclient.filters.bountyfilter
Module Contents
polyswarmclient.filters.bountyfilter.logger[source]
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

is_allowed(self, metadata)[source]

Check metadata against the accept and exclude filters, returning True if it passes all checks

Parameters

metadata (dict) – metadata dict to test

Returns

True if meets the conditions and passes the filter

Return type

(bool)

polyswarmclient.filters.confidencefilter
Module Contents
polyswarmclient.filters.confidencefilter.logger[source]
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
Module Contents
polyswarmclient.filters.filter.logger[source]
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

LT = <[source]
LTE = <=[source]
EQ = ==[source]
GTE = >=[source]
GT = >[source]
CONTAINS = contains[source]
STARTS_WITH = startswith[source]
ENDS_WITH = endswith[source]
REGEX = regex[source]
__repr__(self)[source]
static from_string(value)[source]
class polyswarmclient.filters.filter.Filter(key, comparison, target_value)[source]

Filter some metadata value

__eq__(self, other)[source]
__repr__(self)[source]
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

string_check(self, value)[source]

Check a value as a string with EQ, CONTAINS, STARTS_WITH, ENDS_WITH, and REGEX comparisons

Parameters

value (str|int|float|bytes) – Value to compare against

Returns: (bool) returns True if comparison matches

filter(self, metadata)[source]

Take some metadata, and matches the given key against the target_value and comparison operator for this filter

Parameters

metadata (dict) – Dict of k-v metadata values

Returns: (bool) True if it matches the filter

class polyswarmclient.filters.filter.MetadataFilter[source]

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

static pad_metadata(metadata, min_length)[source]

Pad out the metadata list with None values to match a given length

Parameters
  • metadata (list[dict|None]) – List of metadata dicts

  • min_length (int) – Min size for the metadata list after padding

Returns

list of metadata dicts, or None values

polyswarmclient.liveness
Submodules
polyswarmclient.liveness.exceptions
Module Contents
exception polyswarmclient.liveness.exceptions.LivenessReadError[source]

Bases: polyswarmclient.exceptions.PolyswarmClientException

polyswarmclient.liveness.liveness
Module Contents
polyswarmclient.liveness.liveness.logger[source]
class polyswarmclient.liveness.liveness.Liveness[source]
last_iteration :int[source]
average_wait :int[source]
class polyswarmclient.liveness.liveness.LivenessCheck(loop_iteration_threshold=5, average_wait_threshold=10)[source]

Bases: abc.ABC

get_liveness(self)[source]
check(self)[source]

Determine if participant is running smoothly, based on given inputs

class polyswarmclient.liveness.liveness.Task(recorder, key, start_time)[source]
class polyswarmclient.liveness.liveness.LivenessRecorder[source]

Bases: abc.ABC

waiting_task(self, key, start_time)[source]

Add waiting task, but remove when done

Use: async with liveness.waiting_task(key, start_time):

Parameters
  • key – task key

  • start_time – start time, in any units (either block number or time)

polyswarmclient.liveness.local
Module Contents
polyswarmclient.liveness.local.logger[source]
class polyswarmclient.liveness.local.FileLock(fileno)[source]

Locks a file so that only LivelinessRecorder or LivelinessChecker can access at any moment

acquire(self)[source]
release(self)[source]
acquire_unix(self)[source]
acquire_windows(self)[source]
release_unix(self)[source]
__enter__(self)[source]
__exit__(self, exc_type, exc_val, exc_tb)[source]
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

get_liveness(self)[source]
get_average_task_wait(self)[source]
class polyswarmclient.liveness.local.LocalLivenessRecorder[source]

Bases: polyswarmclient.liveness.liveness.LivenessRecorder

Record liveness data in a tempfile

write_sync(self, content)[source]

Write the given content to the file at the given path.

Parameters

content – content to write into the file

polyswarmclient.producer
Submodules
polyswarmclient.producer.base
Module Contents
polyswarmclient.producer.base.logger[source]
polyswarmclient.producer.base.WAIT_TIME = 20[source]
polyswarmclient.producer.base.KEY_TIMEOUT = 10[source]
polyswarmclient.producer.base.JOB_RESULTS_FORMAT = {}_{}_{}_results[source]
class polyswarmclient.producer.base.Producer(client, redis_uri, queue, time_to_post, bounty_filter=None, confidence_modifier=None, rate_limit=None)[source]
polyswarmclient.producer.job
Module Contents
class polyswarmclient.producer.job.JobRequest[source]
polyswarmd_uri :str[source]
guid :str[source]
index :int[source]
uri :str[source]
artifact_type :int[source]
duration :int[source]
metadata :Optional[Dict[str, Any]][source]
chain :str[source]
ts :int[source]
key[source]
is_expired(self, now=None)[source]
get_artifact_type(self)[source]
asdict(self)[source]
class polyswarmclient.producer.job.JobResponse[source]
index :int[source]
bit :bool[source]
verdict :bool[source]
confidence :float[source]
metadata :str[source]
asdict(self)[source]
polyswarmclient.producer.jobprocessor
Module Contents
polyswarmclient.producer.jobprocessor.logger[source]
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

key :str[source]
jobs :List[JobRequest][source]
results :Dict[int, ScanResult][source]
future :Future[source]
times(self)[source]
time_ratios(self)[source]
__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

is_done(self)[source]

Checks all things to see if it is done :return: true if expired, or has all results

__is_expired(self)[source]

Returns true if any of the jobs are expired

__has_all_results(self)[source]

Returns true if all the jobs have a result

__finish(self)[source]

Set the results in the future and mark done

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)

redis_uri :str[source]
confidence_modifier :Optional[ConfidenceModifier][source]
queue :str[source]
period :float[source]
pending_jobs :Dict[str, PendingJob][source]
job_lock :Optional[asyncio.Lock][source]
redis :Optional[Redis][source]
task[source]
reset_callback[source]
stop(self)[source]

Stop processing jobs

Package Contents
class polyswarmclient.producer.Producer(client, redis_uri, queue, time_to_post, bounty_filter=None, confidence_modifier=None, rate_limit=None)[source]
polyswarmclient.producer.JOB_RESULTS_FORMAT = {}_{}_{}_results[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
Module Contents
class polyswarmclient.ratelimit.abstractratelimit.AbstractRateLimit[source]

Bases: abc.ABC

Abstract class for building a limit for scans, based on a third party requirement (Such as api key limit for a vendor) Allows different implementations

polyswarmclient.ratelimit.redis
Module Contents
polyswarmclient.ratelimit.redis.logger[source]
polyswarmclient.ratelimit.redis.SECONDS = 1[source]
polyswarmclient.ratelimit.redis.MINUTELY_SECONDS = 60[source]
polyswarmclient.ratelimit.redis.HOURLY_SECONDS[source]
polyswarmclient.ratelimit.redis.DAILY_SECONDS[source]
class polyswarmclient.ratelimit.redis.RedisKeyManager[source]

Bases: abc.ABC

get_key(self, prefix)[source]
get_expiration(self)[source]
class polyswarmclient.ratelimit.redis.DateKeyManager(expiration, format_str)[source]

Bases: polyswarmclient.ratelimit.redis.RedisKeyManager

get_key(self, prefix)[source]
get_expiration(self)[source]
class polyswarmclient.ratelimit.redis.DailyKeyManager[source]

Bases: polyswarmclient.ratelimit.redis.DateKeyManager

class polyswarmclient.ratelimit.redis.HourlyKeyManager[source]

Bases: polyswarmclient.ratelimit.redis.DateKeyManager

class polyswarmclient.ratelimit.redis.MinutelyKeyManager[source]

Bases: polyswarmclient.ratelimit.redis.DateKeyManager

class polyswarmclient.ratelimit.redis.SecondlyKeyManager[source]

Bases: polyswarmclient.ratelimit.redis.DateKeyManager

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.

key[source]
set_redis(self, redis)[source]
class polyswarmclient.ratelimit.redis.RedisDailyRateLimit[source]

Bases: polyswarmclient.ratelimit.redis.RedisRateLimit

Submodules

polyswarmclient.abstractambassador
Module Contents
polyswarmclient.abstractambassador.logger[source]
polyswarmclient.abstractambassador.BOUNTY_QUEUE_SIZE[source]
polyswarmclient.abstractambassador.MAX_BOUNTIES_IN_FLIGHT[source]
polyswarmclient.abstractambassador.MAX_BOUNTIES_PER_BLOCK[source]
polyswarmclient.abstractambassador.BLOCK_DIVISOR[source]
class polyswarmclient.abstractambassador.QueuedBounty(artifact_type, amount, ipfs_uri, duration, api_key=None, metadata=None)[source]

Bases: object

__repr__(self)[source]
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

AbstractAmbassador

static generate_metadata(content)[source]

Generate a bunch of metadata for a given bytestream from a file

Parameters

content – bytes-like object (or string)

Returns

dictionary of metadata about a file

run(self)[source]

Run the Client on all of our chains.

polyswarmclient.abstractarbiter
Module Contents
polyswarmclient.abstractarbiter.logger[source]
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

AbstractArbiter

run(self)[source]

Run the Client on the Arbiter’s chains.

polyswarmclient.abstractmicroengine
Module Contents
polyswarmclient.abstractmicroengine.logger[source]
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

AbstractMicroengine

run(self)[source]

Run the Client on the Microengine’s chains.

polyswarmclient.abstractscanner
Module Contents
polyswarmclient.abstractscanner.logger[source]
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

__repr__(self)[source]
class polyswarmclient.abstractscanner.ScanMode[source]

Bases: enum.Enum

Denote whether the Scanner is using asynchronous or synchronous scan

SYNC = 0[source]
ASYNC = 1[source]
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.

get_executor(self)[source]
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

ScanResult

polyswarmclient.backoff_wrapper
Module Contents
polyswarmclient.backoff_wrapper.logger[source]
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

reset(self)[source]
polyswarmclient.bidstrategy
Module Contents
class polyswarmclient.bidstrategy.BidStrategyBase(min_bid_multiplier=None, max_bid_multiplier=None)[source]
polyswarmclient.config
Module Contents
polyswarmclient.config.logger[source]
polyswarmclient.config.validate_apikey(ctx, param, value)[source]
Validates the API key passed in through click parameters
polyswarmclient.config.init_logging(loggers, log_format, loglevel=logging.WARNING)[source]
Logic to support JSON logging.
class polyswarmclient.config.LoggerConfig(loggers, log_format, log_level=logging.WARNING)[source]
LEVELS[source]
configure(self)[source]
set_level(self, new_level)[source]
polyswarmclient.corpus
Module Contents
polyswarmclient.corpus.logger[source]
polyswarmclient.corpus.MALICIOUS_BOOTSTRAP_URL[source]
polyswarmclient.corpus.ARCHIVE_PASSWORD[source]
class polyswarmclient.corpus.DownloadToFileSystemCorpus(base_dir=None)[source]

Bases: object

mal_path[source]
benign_path[source]
download_and_unpack(self)[source]
_get_pth_listing(self, p)[source]
get_malicious_file_list(self)[source]
get_benign_file_list(self)[source]
download_truth(self)[source]
polyswarmclient.events
Module Contents
polyswarmclient.events.logger[source]
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.

register(self, f)[source]

Register a function to this Callback.

Parameters

f (function) – Function to register.

remove(self, f)[source]

Remove a function previously assigned to this Callback.

Parameters

f (function) – Function to remove.

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)

get(self)[source]

Pop the lowest valued block in the queue.

Returns

The lowest valued block in the PriorityQueue.

Return type

(block, event)

put(self, block, event)[source]

Add a tuple (block, event) to the PriorityQueue. Block signifies the priority of the 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.

__eq__(self, other)[source]
__lt__(self, other)[source]
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

class polyswarmclient.exceptions.FatalError(message='', exit_code=0)[source]

Bases: click.ClickException

exception polyswarmclient.exceptions.SecurityWarning[source]

Bases: Warning

Warnings about disabled security features.

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

add_fields(self, log_record, record, message_dict)[source]
polyswarmclient.parameters
Module Contents
class polyswarmclient.parameters.Parameters(p)[source]

Bases: object

Trivial wrapper around a dict but protected via a RWLock to allow updates

polyswarmclient.request_rate_limit
Module Contents
polyswarmclient.request_rate_limit.logger[source]
polyswarmclient.request_rate_limit.RATE_LIMIT_SLEEP = 2[source]
class polyswarmclient.request_rate_limit.RequestRateLimit(event, lock)[source]
polyswarmclient.utils
Module Contents
polyswarmclient.utils.logger[source]
polyswarmclient.utils.TASK_TIMEOUT = 1.0[source]
polyswarmclient.utils.MAX_WAIT[source]
polyswarmclient.utils.MAX_WORKERS = 4[source]
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.to_bytes(value)[source]
polyswarmclient.utils.sha3(seed)[source]
polyswarmclient.utils.int_to_bytes(i)[source]
polyswarmclient.utils.int_from_bytes(b)[source]
polyswarmclient.utils.bool_list_to_int(bs)[source]
polyswarmclient.utils.int_to_bool_list(i, expected_size)[source]
polyswarmclient.utils.guid_as_string(guid)[source]
polyswarmclient.utils.calculate_commitment(account, verdicts, nonce=None)[source]
polyswarmclient.utils.configure_event_loop()[source]
polyswarmclient.utils.asyncio_join()[source]
Gather all remaining tasks, assumes loop is not running
polyswarmclient.utils.asyncio_stop()[source]
Stop the main event loop
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

__del__(self)[source]
__getattr__(self, name)[source]
polyswarmclient.utils.return_on_exception(exceptions=(Exception, ), default=None)[source]
polyswarmclient.utils.finalize_polyswarmd_addr(polyswarmd_addr, api_key, allow_key_over_http, insecure_transport)[source]
polyswarmclient.utils.fill_scheme(polyswarmd_addr, insecure_transport)[source]

Package Contents

class polyswarmclient.BidStrategyBase(min_bid_multiplier=None, max_bid_multiplier=None)[source]
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

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.RequestRateLimit(event, lock)[source]
polyswarmclient.logger[source]
polyswarmclient.MAX_ARTIFACTS = 256[source]
polyswarmclient.RATE_LIMIT_SLEEP = 2.0[source]
polyswarmclient.MAX_BACKOFF = 32[source]
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?

run(self, chains=None)[source]

Run the main event loop

Parameters

chains (set(str)) – Set of chains to operate on. Defaults to {‘home’, ‘side’}

clear_sub_clients(self)[source]
create_ethereum_sub_clients(self, chains)[source]
create_fast_sub_clients(self, chains)[source]
static to_wei(amount, unit='ether')[source]
static from_wei(amount, unit='ether')[source]
static _check_status_for_rate_limit(status)[source]
schedule(self, expiration, event, chain)[source]

Schedule an event to execute on a particular block

Parameters
  • expiration (int) – Which block to execute on

  • event (Event) – Event to trigger on expiration block

  • chain (str) – Which chain to operate on

liveness

Submodules

liveness.__main__
Module Contents
liveness.__main__.main(log, log_format, loop_update_threshold, average_bounty_wait_threshold)[source]

microengine

Subpackages

microengine.bidstrategy
Submodules
microengine.bidstrategy.aggressive
Module Contents
class microengine.bidstrategy.aggressive.BidStrategy[source]

Bases: polyswarmclient.BidStrategyBase

microengine.bidstrategy.conservative
Module Contents
class microengine.bidstrategy.conservative.BidStrategy[source]

Bases: polyswarmclient.BidStrategyBase

microengine.bidstrategy.default
Module Contents
class microengine.bidstrategy.default.BidStrategy[source]

Bases: polyswarmclient.BidStrategyBase

Submodules

microengine.__main__
Module Contents
microengine.__main__.logger[source]
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.__main__.main(log, client_log, polyswarmd_addr, keyfile, password, api_key, backend, testing, insecure_transport, allow_key_over_http, chains, log_format, artifact_type, bid_strategy, accept, exclude, filter, confidence)[source]
Entrypoint for the microengine driver
microengine.clamav
Module Contents
microengine.clamav.logger[source]
microengine.clamav.CLAMD_HOST[source]
microengine.clamav.CLAMD_PORT[source]
microengine.clamav.CLAMD_TIMEOUT = 30.0[source]
class microengine.clamav.Scanner[source]

Bases: polyswarmclient.abstractscanner.AbstractScanner

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
microengine.eicar.logger[source]
microengine.eicar.EICAR[source]
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

ScanResult

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
microengine.multi.logger[source]
microengine.multi.BACKENDS[source]
class microengine.multi.Scanner[source]

Bases: polyswarmclient.abstractscanner.AbstractScanner

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
microengine.producer.logger[source]
microengine.producer.REDIS_ADDR[source]
microengine.producer.QUEUE[source]
microengine.producer.RATE_LIMIT[source]
microengine.producer.TIME_TO_POST_ASSERTION = 6[source]
microengine.producer.KEY_TIMEOUT = 20[source]
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
microengine.scratch.logger[source]
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

ScanResult

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
microengine.yara.logger[source]
microengine.yara.RULES_DIR[source]
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

ScanResult

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.