def run_bridge(): # pylint: disable=too-many-statements runners = [] logger = get_logger(logger_name='runner') required_configs = ['MODE', 'secret_node', 'multisig_acc_addr', 'chain_id'] cfg = Config(required=required_configs) try: configure_secretcli(cfg) except RuntimeError: logger = get_logger(logger_name='runner') logger.error('Failed to set up secretcli') sys.exit(1) if cfg.get('token', ''): signer = Pkcs11CryptoStore(store=cfg["PKCS11_MODULE"], token=cfg["token"], user_pin=cfg["user_pin"], label=cfg.get('label')) else: signer = LocalCryptoStore(private_key=bytes_from_hex( cfg['eth_private_key']), account=cfg['eth_address']) logger.info(f'Starting with ETH address {signer.address}') with database(db=cfg['db_name'], host=cfg['db_host'], password=cfg['db_password'], username=cfg['db_username']): eth_wallet = MultisigWallet(w3, cfg['multisig_wallet_address']) secret_account = SecretAccount(cfg['multisig_acc_addr'], cfg['secret_key_name']) eth_signer = EtherSigner(eth_wallet, signer, dst_network="Secret", config=cfg) s20_signer = Secret20Signer(secret_account, eth_wallet, cfg) runners.append(eth_signer) runners.append(s20_signer) if cfg['MODE'].lower() == 'leader': eth_leader = EtherLeader(eth_wallet, signer, dst_network="Secret", config=cfg) secret_leader = SecretAccount(cfg['multisig_acc_addr'], cfg['multisig_key_name']) s20_leader = Secret20Leader(secret_leader, eth_wallet, src_network="Ethereum", config=cfg) runners.append(eth_leader) runners.append(s20_leader) run_all(runners)
def run_bridge(): # pylint: disable=too-many-statements runners = [] logger = get_logger(logger_name='runner', loglevel=config.log_level) try: configure_secretcli(config) except RuntimeError: logger = get_logger(logger_name='runner', loglevel=config.log_level) logger.error('Failed to set up secretcli') sys.exit(1) if config.token: signer = Pkcs11CryptoStore(store=config.pkcs11_module, token=config.token, user_pin=config.user_pin, label=config.label) else: signer = LocalCryptoStore(private_key=bytes_from_hex( config.eth_private_key), account=config.eth_address) logger.info(f'Starting with ETH address {signer.address}') uri = config.db_uri if not uri: db = config.db_name or 'test_db' host = config.db_host or 'localhost' password = config.db_password username = config.db_username uri = f"mongodb+srv://{username}:{password}@{host}/{db}?retryWrites=true&w=majority" with database(uri): eth_wallet = MultisigWallet(w3, config.multisig_wallet_address) secret_account = SecretAccount(config.multisig_acc_addr, config.secret_key_name) eth_signer = EtherSigner(eth_wallet, signer, config=config) s20_signer = Secret20Signer(secret_account, eth_wallet, config) runners.append(s20_signer) if config.mode.lower() == 'signer': runners.append(eth_signer) if config.mode.lower() == 'leader': eth_leader = EtherLeader(eth_wallet, signer, config=config) secret_leader = SecretAccount(config.multisig_acc_addr, config.multisig_key_name) s20_leader = Secret20Leader(secret_leader, eth_wallet, config=config) runners.append(eth_leader) runners.append(s20_leader) # run_all(runners) run(runners, config)
def __init__(self, contract: MultisigWallet, token_to_secret_map: Dict[str, Token], s20_multisig_account: SecretAccount, config: Config, **kwargs): self.contract = contract self.s20_map = token_to_secret_map self.config = config self.multisig = s20_multisig_account self.event_listener = EthEventListener(contract, config) self.logger = get_logger( db_name=self.config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.multisig.name}")) self.stop_signal = Event() self.account_num = 0 self.sequence_lock = Lock() self.sequence = 0 self.update_sequence() self.event_listener.register( self._handle, contract.tracked_event(), ) super().__init__(group=None, name="SecretManager", target=self.run, **kwargs)
def __init__( self, multisig_wallet: MultisigWallet, signer: CryptoManagerBase, config: Config, **kwargs ): self.config = config self.multisig_wallet = multisig_wallet self.erc20 = erc20_contract() self.pending_txs: List[str] = [] self.token_map = {} self.signer = signer self._coins = CoinHandler() self.logger = get_logger( db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or self.__class__.__name__ ) self.stop_event = Event() self.threads = { 'confirmer': EthConfirmer(self.multisig_wallet, self.logger), 'events': EthEventListener(self.multisig_wallet, config) } super().__init__(group=None, name="EtherLeader", target=self.run, **kwargs)
def __init__(self, multisig_wallet: MultisigWallet, signer: CryptoManagerBase, dst_network: str, config: Config, **kwargs): self.config = config self.multisig_wallet = multisig_wallet self.erc20 = erc20_contract() self.pending_txs: List[str] = [] token_map = {} confirmer_token_map = {} pairs = TokenPairing.objects(dst_network=dst_network, src_network=self.network) for pair in pairs: token_map.update( {pair.dst_address: Token(pair.src_address, pair.src_coin)}) confirmer_token_map.update( {pair.src_address: Token(pair.dst_address, pair.dst_coin)}) self.signer = signer self.token_map = token_map self.logger = get_logger(db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or self.__class__.__name__) self.stop_event = Event() self.confirmer = EthConfirmer(self.multisig_wallet, confirmer_token_map, self.logger) self.event_listener = EthEventListener(self.multisig_wallet, config) self.stop_event = Event() super().__init__(group=None, name="EtherLeader", target=self.run, **kwargs)
def __init__(self, secret_multisig: SecretAccount, contract: MultisigWallet, src_network: str, config: Config, *args, **kwargs): super().__init__(*args, **kwargs) token_map = {} pairs = TokenPairing.objects(dst_network=self.network, src_network=src_network) for pair in pairs: token_map.update( {pair.src_address: Token(pair.dst_address, pair.dst_coin)}) self.multisig_name = secret_multisig.name self.config = config self.manager = SecretManager(contract, token_map, secret_multisig, config) self.logger = get_logger( db_name=self.config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.multisig_name}")) self.stop_event = Event() super().__init__(group=None, name="SecretLeader", target=self.run, **kwargs)
def __init__(self, multisig_wallet: MultisigWallet, signer: CryptoManagerBase, dst_network: str, config: Config, **kwargs): self.config = config self.multisig_wallet = multisig_wallet self.erc20 = erc20_contract() token_map = {} pairs = TokenPairing.objects(dst_network=dst_network, src_network=self.network) for pair in pairs: token_map.update( {pair.dst_address: Token(pair.src_address, pair.src_coin)}) self.signer = signer # self.private_key = private_key # self.default_account = account self.token_map = token_map self.logger = get_logger(db_name=self.config['db_name'], logger_name=config.get( 'logger_name', self.__class__.__name__)) self.stop_event = Event() super().__init__(group=None, name="EtherLeader", target=self.run, **kwargs)
def __init__(self, contract: MultisigWallet, s20_multisig_account: SecretAccount, config: Config, **kwargs): self.contract = contract self._coins = CoinHandler() self.config = config self.multisig = s20_multisig_account self.event_listener = EthEventListener(contract, config) self.logger = get_logger( db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or f"{self.__class__.__name__}-{self.multisig.name}") self.stop_signal = Event() self.account_num = 0 self.sequence_lock = Lock() self.sequence = 0 self.update_sequence() self.event_listener.register( self._handle, contract.tracked_event(), ) super().__init__(group=None, name="SecretManager", target=self.run, **kwargs)
def __init__(self, multisig_wallet: MultisigWallet, private_key: bytes, account: str, config: Config, **kwargs): self.config = config self.multisig_wallet = multisig_wallet self.private_key = private_key self.default_account = account self.logger = get_logger(db_name=self.config['db_name'], logger_name=config.get('logger_name', self.__class__.__name__)) self.stop_event = Event() super().__init__(group=None, name="EtherLeader", target=self.run, **kwargs)
def run_bridge(): # pylint: disable=too-many-statements runners = [] required_configs = [ 'SRC_COIN', 'DST_COIN', 'MODE', 'private_key', 'account', 'secret_node', 'multisig_acc_addr', 'chain_id' ] cfg = Config(required=required_configs) try: configure_secretcli(cfg) except RuntimeError: logger = get_logger(logger_name='runner') logger.error('Failed to set up secretcli') sys.exit(1) with database(db=cfg['db_name'], host=cfg['db_host'], password=cfg['db_password'], username=cfg['db_username']): eth_wallet = MultisigWallet(w3, cfg['multisig_wallet_address']) private_key = bytes_from_hex(cfg['private_key']) account = cfg['account'] erc20_contract = '' secret_account = SecretAccount(cfg['multisig_acc_addr'], cfg['secret_key_name']) if NETWORK_PARAMS[cfg['SRC_COIN']]['type'] == 'erc20': token = get_token(cfg['SRC_COIN'], cfg['network']) erc20_contract = Erc20(w3, token, eth_wallet.address) src_signer = ERC20Signer(eth_wallet, token, private_key, account, cfg) dst_signer = Secret20Signer(erc20_contract, secret_account, cfg) else: src_signer = EtherSigner(eth_wallet, private_key, account, cfg) dst_signer = Secret20Signer(eth_wallet, secret_account, cfg) runners.append(src_signer) runners.append(dst_signer) if cfg['MODE'].lower() == 'leader': src_leader = get_leader(cfg['SRC_COIN'], eth_wallet, private_key, account, cfg) if erc20_contract: dst_leader = get_leader(cfg['DST_COIN'], erc20_contract, private_key, account, cfg) else: dst_leader = get_leader(cfg['DST_COIN'], eth_wallet, private_key, account, cfg) runners.append(src_leader) runners.append(dst_leader) run_all(runners)
def __init__(self, multisig_wallet: MultisigWallet, private_key: bytes, account: str, config: Config): # todo: simplify this, pylint is right self.multisig_wallet = multisig_wallet self.private_key = private_key self.account = account self.config = config self.logger = get_logger(db_name=config['db_name'], logger_name=config.get('logger_name', f"{self.__class__.__name__}-{self.account[0:5]}")) self.submissions_lock = Lock() self.catch_up_complete = False self.cache = self._create_cache() self.thread_pool = ThreadPoolExecutor()
def __init__(self, multisig: SecretAccount, contract: MultisigWallet, config: Config, **kwargs): self.multisig = multisig self.contract = contract self.config = config self.stop_event = Event() self.logger = get_logger(db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or f"SecretSigner-{self.multisig.name}") super().__init__(group=None, name=f"SecretSigner-{self.multisig.name}", target=self.run, **kwargs) self.setDaemon(True) # so tests don't hang self.account_num, _ = self._account_details()
def __init__(self, contract: EthereumContract, config: Config, **kwargs): # Note: each event listener can listen to one contract at a time self.id = next(self._ids) self.contract = contract self.config = config self.callbacks = Callbacks() self.logger = get_logger(db_name=config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.id}")) self.events = [] self.stop_event = Event() self.confirmations = config['eth_confirmations'] super().__init__(group=None, name=f"EventListener-{config.get('logger_name', '')}", target=self.run, **kwargs)
def __init__(self, multisig_contract: MultisigWallet, signer: CryptoManagerBase, config: Config): # todo: simplify this, pylint is right self.multisig_contract = multisig_contract self.account = signer.address self.signer = signer self.config = config self.logger = get_logger( db_name=config.db_name, loglevel=self.config.log_level, logger_name=config.logger_name or f"{self.__class__.__name__}-{self.account[0:5]}") self.erc20 = erc20_contract() self.catch_up_complete = False self.coins = CoinHandler()
def __init__(self, contract: MultisigWallet, signer: CryptoManagerBase, dst_network: str, config: Config, **kwargs): self.account = signer.address self.event_listener = EthEventListener(contract, config) self.stop_event = Event() self.logger = get_logger( db_name=config.db_name, logger_name=config.logger_name or f"{self.__class__.__name__}-{self.account[0:5]}") self.config = config self.signer = EthSignerImpl(contract, signer, dst_network, config) super().__init__(group=None, name=f"{self.__class__.__name__}-{self.account[0:5]}", target=self.run, **kwargs) self.setDaemon(True) # so tests don't hang
def __init__(self, secret_multisig: SecretAccount, s20_contract: Token, contract: EthereumContract, config: Config, *args, **kwargs): super().__init__(*args, **kwargs) self.multisig_name = secret_multisig.name self.config = config self.manager = SecretManager(contract, s20_contract, secret_multisig, config) self.logger = get_logger( db_name=self.config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.multisig_name}")) self.stop_event = Event() super().__init__(group=None, name="SecretLeader", target=self.run, **kwargs)
def __init__(self, contract: MultisigWallet, private_key: bytes, account: str, config: Config, **kwargs): self.account = account self.private_key = private_key self.event_listener = EthEventListener(contract, config) self.stop_event = Event() self.logger = get_logger( db_name=config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.account[0:5]}")) self.signer = EthSignerImpl(contract, self.private_key, self.account, config) super().__init__(group=None, name=f"{self.__class__.__name__}-{self.account[0:5]}", target=self.run, **kwargs)
def __init__(self, secret_multisig: SecretAccount, contract: MultisigWallet, config: Config, *args, **kwargs): super().__init__(*args, **kwargs) self.multisig_name = secret_multisig.name self.config = config self.manager = SecretManager(contract, secret_multisig, config) self.logger = get_logger( db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or f"{self.__class__.__name__}-{self.multisig_name}") self.stop_event = Event() super().__init__(group=None, name="SecretLeader", target=self.run, **kwargs)
def __init__(self, contract: EthereumContract, config: Config, **kwargs): # Note: each event listener can listen to one contract at a time self.id = next(self._ids) self.tracked_contract = contract self.config = config self.callbacks = Callbacks() self.logger = get_logger(db_name=config.db_name, loglevel=config.log_level, logger_name=config.logger_name or f"{self.__class__.__name__}-{self.id}") self.events = [] self.pending_events: List[Tuple[str, LogReceipt]] = [] self.filters: Dict[str, LogFilter] = {} self.confirmations = config.eth_confirmations self.stop_event = Event() super().__init__(group=None, name=f"EventListener-{config.logger_name}", target=self.run, **kwargs) self.setDaemon(True)
def __init__(self, multisig_contract: MultisigWallet, signer: CryptoManagerBase, dst_network: str, config: Config): # todo: simplify this, pylint is right self.multisig_contract = multisig_contract self.account = signer.address self.signer = signer self.config = config self.logger = get_logger( db_name=config['db_name'], logger_name=config.get( 'logger_name', f"{self.__class__.__name__}-{self.account[0:5]}")) self.erc20 = erc20_contract() self.catch_up_complete = False self.token_map = {} pairs = TokenPairing.objects(dst_network=dst_network, src_network=self.network) for pair in pairs: self.token_map.update( {pair.src_address: Token(pair.dst_address, pair.dst_coin)}) self.tracked_tokens = self.token_map.keys()
import os import json import subprocess from shutil import copyfile from subprocess import PIPE, run as subprocess_run from typing import List, Dict from src.contracts.secret.secret_contract import swap_json from src.util.config import Config from src.util.logger import get_logger logger = get_logger(logger_name="SecretCLI") def query_encrypted_error(tx_hash: str): cmd = ['secretcli', 'q', 'compute', 'tx', tx_hash] resp = run_secret_cli(cmd) resp_json = json.loads(resp) return resp_json["output_error"] def sign_tx(unsigned_tx_path: str, multi_sig_account_addr: str, account_name: str, account: int, sequence: int): cmd = [ 'secretcli', 'tx', 'sign', unsigned_tx_path, '--signature-only', '--multisig', multi_sig_account_addr, '--from', account_name, '--offline', '--account-number', str(account), '--sequence', str(sequence) ]
import os import json import subprocess from shutil import copyfile from subprocess import PIPE, run as subprocess_run from typing import List, Dict from retry import retry from src.contracts.secret.secret_contract import swap_json from src.util.config import Config, config from src.util.logger import get_logger logger = get_logger(logger_name="SecretCLI", loglevel=config.log_level) def query_encrypted_error(tx_hash: str): cmd = ['secretcli', 'q', 'compute', 'tx', tx_hash] resp = run_secret_cli(cmd) resp_json = json.loads(resp) return resp_json["output_error"] def sign_tx(unsigned_tx_path: str, multi_sig_account_addr: str, account_name: str, account: int, sequence: int): cmd = [ 'secretcli', 'tx', 'sign', unsigned_tx_path, '--signature-only', '--multisig', multi_sig_account_addr, '--from', account_name, '--offline', '--account-number', str(account), '--sequence',
train=False).save_dataset(tmp_file.estimate_set()) def train(): Processor().train() def cross_validation(): Processor().cross_validation() def predict(): Processor(Model.load()).predict() if __name__ == '__main__': logger = logger.get_logger('main') args = sys.argv try: task = args[1] except IndexError: logger.info('Please set task in args.') sys.exit() if task == 'prepare_data': logger.info('Execute task: prepare data.') prepare_data() elif task == 'preprocess': logger.info('Execute task: preprocess.') preprocess() elif task == 'cross_validation': logger.info('Execute task: cross_validation.') cross_validation()
from json import dumps from flask import Response from src.exceptions.exception import GenericAPIException from src.util.logger import get_logger log = get_logger() class ExceptionHandler: def api_exception(self, exception: GenericAPIException): log.error( f"[API ERROR] Error during request process {exception.message}") error_json = dumps(exception.to_dict()) return Response(error_json, status=exception.status_code) def generic_exception(self, exception: Exception): log.error( f"[API UNKOWN ERROR] Error during request process {str(exception)}" ) return Response(str(exception), status=500)
import qrcode from datetime import datetime, timedelta from time import time from src.util.logger import get_logger import json import math from PIL import Image, ImageDraw, ImageFont import textwrap import config logger = get_logger() QR_CODE_BOX_SIZE = 15 # Pixel size per box. QR_CODE_VERSION = None # Auto-resize QR code QR_CODE_BORDER = 0 QR_CODE_ERROR_CORRECTION = qrcode.constants.ERROR_CORRECT_M QR_CODE_DESCRIPTION_MAX_LENGTH = 100 # For Brother QL-810W with 62 mm wide labels PRINTER_HEIGHT_MARGIN_MM = 3 PRINTER_PIXELS_PER_MM = 300 / 25.4 PRINTER_LABEL_PRINTABLE_WIDTH = 58 IMG_WIDTH = math.floor(PRINTER_PIXELS_PER_MM * PRINTER_LABEL_PRINTABLE_WIDTH) IMG_HEIGHT = math.floor((58 + 20) / 25.4 * 300) IMG_MARGIN = 48 # Versions of different types of QR codes QR_VERSION_BOX_LABEL = 2 QR_VERSION_WARNING_LABEL = 1 QR_VERSION_TEMP_STORAGE_LABEL = 1
import pytest from selenium import webdriver from selenium.webdriver.remote.webdriver import WebDriver from webdriver_manager.chrome import ChromeDriverManager from run_config import BROWSER from src.util.logger import get_logger log = get_logger(__name__) @pytest.fixture(scope='function') def browser() -> WebDriver: driver = None if BROWSER == 'chrome': driver = webdriver.Chrome(ChromeDriverManager().install()) else: pytest.exit(f'unsupported browser {BROWSER} in configuration', 3) yield driver driver.quit()
import os import time import numpy as np import torch from tqdm import tqdm from shutil import copyfile from src.algorithm.verinet import VeriNet from src.algorithm.verinet_util import Status from src.algorithm.verification_objectives import LocalRobustnessObjective from src.data_loader.onnx_parser import ONNXParser from src.util.logger import get_logger from src.util.config import * benchmark_logger = get_logger(LOGS_LEVEL, __name__, "../../logs/", "benchmark_log") # noinspection PyArgumentList,PyShadowingNames def run_benchmark(images: np.array, epsilons: list, model_path: str, mean: np.array, std: np.array, timeout: int, result_path: str, targets: np.array = None, max_procs: int = None, max_val: int = 1, gradient_step: float = 1e-1 ):
# -*- coding: utf-8 -*- import sys from sqlalchemy import create_engine from src.util.logger import get_logger from sqlalchemy.orm import sessionmaker logger = get_logger(sys.argv[0]) logger.info("Criando conexão com o banco de dados") engine = create_engine('mysql://*****:*****@172.10.0.2:3306/AirQuality', echo=True) logger.info("Inicializando pool de conexões") Session = sessionmaker(bind=engine) def get_session(): logger.info('Criando sessão') try: return Session() except: logger.error("Não foi possível criar sessão")