async def _mixing_initiate_loop(self): # Task 4. Initiate mixing epochs contract_concise = ConciseContract(self.contract) K = contract_concise.K() # noqa: N806 while True: # Step 4.a. Wait until there are k values then call initiate_mix while True: inputs_ready = contract_concise.inputs_ready() mixes_avail = contract_concise.mixes_available() if inputs_ready >= K and mixes_avail >= 1: break await asyncio.sleep(5) # Step 4.b. Call initiate mix tx_hash = self.contract.functions.initiate_mix().transact( {"from": self.w3.eth.accounts[0]} ) tx_receipt = await wait_for_receipt(self.w3, tx_hash) rich_logs = self.contract.events.MixingEpochInitiated().processReceipt( tx_receipt ) if rich_logs: epoch = rich_logs[0]["args"]["epoch"] logging.info(f"[{self.myid}] Mixing epoch initiated: {epoch}") else: logging.info(f"[{self.myid}] initiate_mix failed (redundant?)") await asyncio.sleep(10)
async def send_message(self, m): # Submit a message to be mixed contract_concise = ConciseContract(self.contract) # Step 1. Wait until there is input available, and enough triples while True: inputmasks_available = contract_concise.inputmasks_available() # logging.infof'inputmasks_available: {inputmasks_available}') if inputmasks_available >= 1: break await asyncio.sleep(5) # Step 2. Reserve the input mask tx_hash = self.contract.functions.reserve_inputmask().transact( {"from": self.w3.eth.accounts[0]} ) tx_receipt = await wait_for_receipt(self.w3, tx_hash) rich_logs = self.contract.events.InputMaskClaimed().processReceipt(tx_receipt) if rich_logs: inputmask_idx = rich_logs[0]["args"]["inputmask_idx"] else: raise ValueError # Step 3. Fetch the input mask from the servers inputmask = await self._get_inputmask(inputmask_idx) message = int.from_bytes(m.encode(), "big") maskedinput = message + inputmask maskedinput_bytes = self.w3.toBytes(hexstr=hex(maskedinput.value)) maskedinput_bytes = maskedinput_bytes.rjust(32, b"\x00") # Step 4. Publish the masked input tx_hash = self.contract.functions.submit_message( inputmask_idx, maskedinput_bytes ).transact({"from": self.w3.eth.accounts[0]}) tx_receipt = await wait_for_receipt(self.w3, tx_hash)
def send_asset(self, contract_name, to_addr, amount, memo=None): contract_instance = self.erc20_contracts.get(contract_name, None) if contract_instance == None: raise Exception('Not supported contract name for swap:%s' % contract_name) if not web3.isChecksumAddress(to_addr): to_addr = web3.toChecksumAddress(to_addr) contract = ConciseContract(contract_instance) if not web3.personal.unlockAccount(config.ETHEREUM_SCAN_ADDRESS, config.ETHEREUM_SCAN_PASSWD): raise Exception('Failed to unlcok account:' % config.ETHEREUM_SCAN_ADDRESS) amountInWei = self.Satoshi2Wei(amount, contract.decimals())[0] gas_price = web3.eth.gasPrice transact = contract_instance.functions.transferFrom( config.ETHEREUM_SCAN_ADDRESS, to_addr, amountInWei) gas = transact.estimateGas() ret = transact.transact( transaction={ 'from': config.ETHEREUM_SCAN_ADDRESS, 'gas': gas, 'gasPrice': gas_price }) if not ret: raise Exception('Failed to send_asset:[%s, %s, %s]' % (contract_name, to_addr, amount)) return ret.hex()
def __init__(self, pool, node, uniswapex_addr, uniswap_factory_addr, start_at, blacklist): self.pool = pool self.node = node self.w3 = Web3(Web3.HTTPProvider(node)) self.watcher = Watcher(self.w3) self.last_block = start_at self.uniswap_cache = {} self.token_blacklist = set() for token in blacklist.split(','): self.token_blacklist.add(token.lower()) self.uniswap_ex = self.w3.eth.contract( address=self.w3.toChecksumAddress(uniswapex_addr), abi=uniswap_ex.abi, ) self.uniswap_factory = self.w3.eth.contract( address=self.w3.toChecksumAddress(uniswap_factory_addr), abi=uniswap_factory.abi, ) self.uniswap_ex_concise = ConciseContract(self.uniswap_ex) self.uniswap_factory_concise = ConciseContract(self.uniswap_factory) def on_block(block_number): logger.debug("Crawler on block {}".format(block_number)) self.search_for_orders(block_number) self.watcher.on_new_block(on_block)
def __init__(self, pool, node, pk, gas_multiplier, uniswapex_addr, whitelisted): self.pool = pool self.node = node self.w3 = Web3(Web3.HTTPProvider(node)) self.watcher = Watcher(self.w3) self.internal_nonce = 0 self.gas_multiplier = gas_multiplier self.account = Account.privateKeyToAccount(pk.replace('0x', '')) self.w3.eth.setGasPriceStrategy(fast_gas_price_strategy) self.whitelisted_tokens = set() for token in whitelisted.split(','): self.whitelisted_tokens.add(token.lower()) self.uniswap_ex = self.w3.eth.contract( address=self.w3.toChecksumAddress(uniswapex_addr), abi=uniswap_ex.abi, ) self.uniswap_ex_concise = ConciseContract(self.uniswap_ex) def on_block(block_number): logger.debug("Executor on block {}".format(block_number)) self.check_open_orders() self.watcher.on_new_block(on_block) logger.info("Using account {}".format(self.account.address))
def __init__(self, account=None, ip_address=None, mac_address=None, w3=None, client_number: int = None): ''' Default constructor of the interface class, with parameters that make the code much cleaner in our client API . For now the only parameter is the client number which identifies which of the default accounts provided by ganache-cli the client sets as its default one {1 - 9} since 0 is for the server and owner of the contract ''' # In case there's no w3 given we initialize to the default server if w3 is None: self.w3 = Web3(HTTPProvider("http://localhost:8545")) #self.w3 = Web3(HTTPProvider("http://192.168.0.29:8545")) else: self.w3 = w3 # Regular register (not from proxy) if ip_address is None and mac_address is None: self.IP = utils.getIP() self.MAC = utils.getMAC() else: self.IP = ip_address self.MAC = mac_address self.contract = self._getContract(self.w3) #self.contract = self._load_contract(self.w3) # The ConciseContract class is much better for reaidng variables straight away. # If our goal is not transact something, we'll use the Concise version of the contract self.contractConcise = ConciseContract(self.contract) # set the default account for the client, if it's None we'll register and we'll get a new one # Only for tests if client_number is not None: self.w3.eth.defaultAccount = self.w3.eth.accounts[client_number] self.account = self.w3.eth.defaultAccount else: # Usamos el w3 del proxy en ese caso # The client's own address is in the account variable self.account = account # The default account is however the one of the server # DATA FOR LEASES: # The dictionary is of the shape { grant_id : amount } so for the total memory we # just add the values self.remoteStorage = {} # The dictionary is of the shape { grant_id : amount } where amount is a number from # 0 to 100. 100 would mean that the amount is equal to all the available storage on # the remote server self.remoteCPU = {} # Load the reservations self._load_reservations()
def get_asset_balance(cls, contract_name): contract = cls.erc20_contracts.get(contract_name, None) if contract == None: raise Exception('Not supported contract name for swap:%s' % contract_name) concise = ConciseContract(contract) return cls.Wei2Satoshi(concise.balanceOf(config.ETHEREUM_SCAN_ADDRESS), concise.decimals())[0]
def factory(w3, exchange_template): deploy = create_contract(w3, 'build/contracts/UniswapFactory.json') tx_hash = deploy.constructor().transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) contract = ConciseContract( w3.eth.contract(address=tx_receipt.contractAddress, abi=deploy.abi)) contract.initializeFactory(exchange_template.address, transact={}) return contract
def exchange_factory(w3, exchange_template): deploy = create_contract(w3, 'contracts/uniswap_factory.vy') tx_hash = deploy.constructor().transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) factory_contract = ConciseContract( w3.eth.contract(address=tx_receipt.contractAddress, abi=deploy.abi)) factory_contract.initializeFactory(exchange_template.address, transact={}) return factory_contract
def erc20_approve(w3, erc20_address, from_addr, to_addr, amount, gas, gas_price): erc20_abi = open('erc20.abi', 'rt').read() erc20 = w3.eth.contract(abi = erc20_abi, address = erc20_address) concise = ConciseContract(erc20) txn_hash = concise.approve(to_addr, amount, transact = {'from': from_addr, 'gas': gas, 'gasPrice': gas_price}) return wait_to_be_mined(w3, txn_hash)
def data(web3, Data, constants, user0): _priv, owner = user0 deploy_txn = Data.deploy() deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn) assert deploy_receipt is not None _contract = Data(address=deploy_receipt['contractAddress']) concise_contract = ConciseContract(_contract) assert owner == concise_contract.owner() return concise_contract
def mp3(web3, Mp3, user0): _priv, owner = user0 deploy_txn = Mp3.deploy() deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn) assert deploy_receipt is not None _contract = Mp3(address=deploy_receipt['contractAddress']) concise_contract = ConciseContract(_contract) assert owner == concise_contract.owner() return concise_contract
async def main_loop(w3): pp_elements = PreProcessedElements() # deletes sharedata/ if present pp_elements.clear_preprocessing() # Step 1. # Create the coordinator contract and web3 interface to it compiled_sol = compile_source( open(os.path.join(os.path.dirname(__file__), "asynchromix.sol")).read()) # Compiled source code contract_interface = compiled_sol["<stdin>:AsynchromixCoordinator"] contract_class = w3.eth.contract(abi=contract_interface["abi"], bytecode=contract_interface["bin"]) # tx_hash = contract_class.constructor(w3.eth.accounts[:7],2).transact( # {'from':w3.eth.accounts[0]}) # n=7, t=2 tx_hash = contract_class.constructor(w3.eth.accounts[:4], 1).transact( {"from": w3.eth.accounts[0]}) # n=4, t=1 # Get tx receipt to get contract address tx_receipt = await wait_for_receipt(w3, tx_hash) contract_address = tx_receipt["contractAddress"] if w3.eth.getCode(contract_address) == b"": logging.critical( "code was empty 0x, constructor may have run out of gas") raise ValueError # Contract instance in concise mode abi = contract_interface["abi"] contract = w3.eth.contract(address=contract_address, abi=abi) contract_concise = ConciseContract(contract) # Call read only methods to check n = contract_concise.n() # Step 2: Create the servers router = SimpleRouter(n) sends, recvs = router.sends, router.recvs servers = [ AsynchromixServer("sid", i, sends[i], recvs[i], w3, contract) for i in range(n) ] # Step 3. Create the client async def req_mask(i, idx): # client requests input mask {idx} from server {i} return servers[i]._inputmasks[idx] client = AsynchromixClient("sid", "client", None, None, w3, contract, req_mask) # Step 4. Wait for conclusion for i, server in enumerate(servers): await server.join() await client.join()
def factory(w3, account_template): deploy = create_contract(w3, './contracts/AccountFactory.vy') tx_hash = deploy.constructor().transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) contract = ConciseContract(w3.eth.contract( address=tx_receipt.contractAddress, abi=deploy.abi )) contract.__init__(account_template.address, transact={}) return contract
def crowdsale(web3, Crowdsale, user0, user2): _priv, owner = user0 _priv, crowdsale_wallet = user2 deploy_txn = Crowdsale.deploy(args=[crowdsale_wallet]) deploy_receipt = wait_for_transaction_receipt(web3, deploy_txn) assert deploy_receipt is not None _contract = Crowdsale(address=deploy_receipt['contractAddress']) concise_contract = ConciseContract(_contract) assert owner == concise_contract.owner() return concise_contract
def factory(w3, eth_flash_template, erc20_flash_template): deploy = create_contract(w3, 'contracts/uniflash_factory.vy') tx_hash = deploy.constructor().transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) contract = ConciseContract( w3.eth.contract(address=tx_receipt.contractAddress, abi=deploy.abi)) contract.initFactory(eth_flash_template.address, erc20_flash_template.address, transact={}) return contract
class Controller: def __init__(self, name): print('initializing connection to Blockchain...') #Make connection and get sol compiled code web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545")) compiled_sol = compile_source(contract_source_code) # Compiled source code contract_interface = compiled_sol['<stdin>:Root'] permission_interface = compiled_sol['<stdin>:GetPermission'] data_interface = compiled_sol['<stdin>:HashedData'] cert_interface = compiled_sol['<stdin>:Certificate'] #Take basic info for initialization account = input('Please enter Ganache Account: ') Blockchain_Address = input('Please enter the address of the root contract: ') #Handling 2048 bits RSA Key Pair psswd = '9592bbc15e5347e284724844d0699454b42ce456bc0eda514a6ad8ad87397544' KeyFile = name + 'RSAKey.bin' if os.path.exists(KeyFile) == False: key = RSA.generate(1024) encryptedKey = key.export_key(passphrase=psswd, pkcs=8, protection="scryptAndAES128-CBC") publicSavedKey = key.publickey().export_key() publickeyOutput = open('Public'+KeyFile, "wb") publickeyOutput.write(publicSavedKey) output = open(KeyFile, "wb") output.write(encryptedKey) else: encodedKey = open(KeyFile, "rb").read() key = RSA.import_key(encodedKey, passphrase=psswd) self.Public_Key = key.publickey().export_key() self.Private_Key = key#key#.export_key() #Connect to deploted contracts web3.eth.defaultAccount = web3.eth.accounts[int(account)] address = Web3.toChecksumAddress(Blockchain_Address) rootContract = web3.eth.contract(address, abi=contract_interface['abi']) self.root = ConciseContract(rootContract) readAddress = self.root.GetReadAddress() raddress = Web3.toChecksumAddress(readAddress) readContract = web3.eth.contract(raddress, abi=permission_interface['abi']) self.read = ConciseContract(readContract) writeAddress = self.root.GetWriteAddress() waddress = Web3.toChecksumAddress(writeAddress) writeContract = web3.eth.contract(waddress, abi=permission_interface['abi']) self.write = ConciseContract(writeContract) dataAddress = self.root.GetGlobalDataAddress() daddress = Web3.toChecksumAddress(dataAddress) dataContract = web3.eth.contract(daddress, abi=data_interface['abi']) self.dataMem = ConciseContract(dataContract) certAddress = self.root.GetCertificateAddress() caddress = Web3.toChecksumAddress(certAddress) certContract = web3.eth.contract(caddress, abi=cert_interface['abi']) self.cert = ConciseContract(certContract)
def test_factory(w3, exchange_template, HAY_token, factory, pad_bytes32, exchange_abi, assert_fail): a0, a1 = w3.eth.accounts[:2] # Can't call initializeFactory on factory twice with raises(TransactionFailed): factory.initializeFactory(HAY_token.address) # Factory initial state assert factory.exchangeTemplate() == exchange_template.address assert factory.getExchange(HAY_token.address) == None # Create Exchange for MRS Token factory.createExchange(HAY_token.address, transact={}) HAY_exchange_address = factory.getExchange(HAY_token.address) assert HAY_exchange_address != None HAY_exchange = ConciseContract( w3.eth.contract(address=HAY_exchange_address, abi=exchange_abi)) assert factory.getToken(HAY_exchange.address) == HAY_token.address assert factory.tokenCount() == 1 assert factory.getTokenWithId(1) == HAY_token.address # Exchange already exists with raises(TransactionFailed): factory.createExchange(HAY_token.address) # Can't call setup on exchange assert_fail(lambda: HAY_exchange.setup(factory.address)) # Exchange initial state assert HAY_exchange.name() == pad_bytes32('Marswap V1') assert HAY_exchange.symbol() == pad_bytes32('MRS-V1') assert HAY_exchange.decimals() == 18 assert HAY_exchange.totalSupply() == 0 assert HAY_exchange.tokenAddress() == HAY_token.address assert HAY_exchange.factoryAddress() == factory.address assert w3.eth.getBalance(HAY_exchange.address) == 0 assert HAY_token.balanceOf(HAY_exchange.address) == 0
def DEN_exchange(w3, exchange_abi, factory, DEN_token): factory.createExchange(DEN_token.address, transact={}) exchange_address = factory.getExchange(DEN_token.address) exchange = ConciseContract( w3.eth.contract(address=exchange_address, abi=exchange_abi)) DEN_token.approve(exchange_address, DEN_RESERVE, transact={}) exchange.addLiquidity(0, DEN_RESERVE, DEADLINE, transact={'value': ETH_RESERVE}) return exchange
def get_token_precision(self, token_address): token_contract = ConciseContract( self.network.web3.eth.contract( address=Web3.toChecksumAddress(token_address), abi=ERC20_BASIC_ABI, ) ) time.sleep(0.5) # we don't want to spam the API try: return token_contract.decimals() except (OverflowError, BadFunctionCallOutput): return
def HAY_exchange(w3, exchange_abi, factory, HAY_token): factory.createExchange(HAY_token.address, transact={}) exchange_address = factory.getExchange(HAY_token.address) exchange = ConciseContract( w3.eth.contract(address=exchange_address, abi=exchange_abi)) HAY_token.approve(exchange_address, HAY_RESERVE, transact={}) exchange.addLiquidity(0, HAY_RESERVE, DEADLINE, transact={'value': ETH_RESERVE}) print('exchange.totalSupply()') print(exchange.totalSupply()) return exchange
def test_factory(w3, exchange_template, HAY_token, exchange_factory, pad_bytes32, exchange_abi): a0, a1 = w3.eth.accounts[:2] # Factory initial state assert exchange_factory.exchangeTemplate() == exchange_template.address assert exchange_factory.getExchange(HAY_token.address) == None # Create Exchange for UNI Token exchange_factory.createExchange(HAY_token.address, transact={}) HAY_exchange_address = exchange_factory.getExchange(HAY_token.address) assert HAY_exchange_address != None HAY_exchange = ConciseContract(w3.eth.contract(address=HAY_exchange_address, abi=exchange_abi)) assert exchange_factory.getToken(HAY_exchange.address) == HAY_token.address assert exchange_factory.tokenCount() == 1 assert exchange_factory.getTokenWithId(1) == HAY_token.address # # Can't call initializeFactory on factory twice # assert_tx_failed(lambda: exchange_factory.initializeFactory(HAY_token.address)) # # Exchange already exists # assert_tx_failed(lambda: exchange_factory.createExchange(HAY_token.address)) # # Can't call setup on exchange # assert_tx_failed(lambda: HAY_exchange.setup(exchange_factory.address)) # # Exchange initial state assert HAY_exchange.name() == pad_bytes32('Uniswap V1') assert HAY_exchange.symbol() == pad_bytes32('UNI-V1') assert HAY_exchange.decimals() == 18 assert HAY_exchange.totalSupply() == 0 assert HAY_exchange.tokenAddress() == HAY_token.address assert HAY_exchange.factoryAddress() == exchange_factory.address assert w3.eth.getBalance(HAY_exchange.address) == 0 assert HAY_token.balanceOf(HAY_exchange.address) == 0
async def _get_inputmask(self, idx): # Private reconstruct contract_concise = ConciseContract(self.contract) n = contract_concise.n() poly = polynomials_over(field) eval_point = EvalPoint(field, n, use_omega_powers=False) shares = [] for i in range(n): share = self.req_mask(i, idx) shares.append(share) shares = await asyncio.gather(*shares) shares = [(eval_point(i), share) for i, share in enumerate(shares)] mask = poly.interpolate_at(shares, 0) return mask
def get_token_from_token_contract(self, token_address: str) -> Optional[Token]: """ Getting information from token contract and creating Token. Smart contract is taken based on provided address """ token_address = self.unify_address(token_address) token_contract = self.web3.eth.contract(address=token_address, abi=ERC20_BASIC_ABI) concise = ConciseContract(token_contract) try: name = concise.name() symbol = concise.symbol() decimals = concise.decimals() logger.debug(f'Token get from contract with success') except (OverflowError, BadFunctionCallOutput): logger.warning(f'Unable to take token from address: {token_address}') return return Token(name, symbol, token_address, decimals)
def HAY_token(w3): deploy = create_contract(w3, 'contracts/test_contracts/ERC20.vy') tx_hash = deploy.constructor(b'HAY Token', b'HAY', 18, TOTAL_HAY).transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) return ConciseContract( w3.eth.contract(address=tx_receipt.contractAddress, abi=deploy.abi))
def new(self, deployer, gas, isConcise=True): #deployer = args[0] #gas = args[1] """ with open("../contracts/Smallbank.sol", "r") as f: compiled_sol = compile_source(f.read()) contract_interface = compiled_sol['<stdin>:Smallbank'] """ with open(self.path, "r") as f: contract_json = json.loads(f.read()) contract_abi, contract_bytecode = contract_json["abi"], contract_json[ "bytecode"] contract = self.w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) tx_hash = contract.deploy(transaction={'from': deployer, 'gas': gas}) tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash) contract_instance = self.w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_abi) #print print("=" * 40 + "\n" + "New deployed address of [{}]: {}".format( self.path.split("/")[-1], contract_instance.address) + "\n" + "=" * 40 + "\n") if isConcise: concise_instance = ConciseContract(contract_instance) return concise_instance return contract_instance
def DEN_token(w3): deploy = create_contract(w3, 'build/contracts/ERC20Mock.json') tx_hash = deploy.constructor(b'DEN Token', b'DEN', 18, 100000 * 10**18).transact() tx_receipt = w3.eth.getTransactionReceipt(tx_hash) return ConciseContract( w3.eth.contract(address=tx_receipt.contractAddress, abi=deploy.abi))
def init_contract(w3, abi_file, contract_addr): contract_addr = checksum(w3,contract_addr) abi = open(abi_file, 'rt').read() contract = w3.eth.contract(abi = abi, address = contract_addr) concise = ConciseContract(contract) return contract, concise
def deploy_contract(self, contract_name, gas=5000000, args=(), concise=True): """Deploys a contract to the given Ethereum network using Web3 Args: contract_name (str): Name of the contract to deploy. Must already be compiled. provider (HTTPProvider): The Web3 provider to deploy with. gas (int): Amount of gas to use when creating the contract. args (obj): Any additional arguments to include with the contract creation. concise (bool): Whether to return a Contract or ConciseContract instance. Returns: Contract: A Web3 contract instance. """ abi, bytecode = self.get_contract_data(contract_name) contract = self.w3.eth.contract(abi=abi, bytecode=bytecode) # Get transaction hash from deployed contract tx_hash = contract.deploy(transaction={ 'from': self.w3.eth.accounts[0], 'gas': gas }, args=args) # Get tx receipt to get contract address tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash) contract_address = tx_receipt['contractAddress'] contract_instance = self.w3.eth.contract(address=contract_address, abi=abi) print("Successfully deployed {0} contract!".format(contract_name)) return ConciseContract(contract_instance) if concise else contract_instance
def new(self, deployer, gas, isConcise=True): #deployer = args[0] #gas = args[1] """ with open("../contracts/Smallbank.sol", "r") as f: compiled_sol = compile_source(f.read()) contract_interface = compiled_sol['<stdin>:Smallbank'] """ with open(self.path, "r") as f: contract_json = json.loads(f.read()) contract_abi, contract_bytecode = contract_json["abi"], contract_json[ "bytecode"] contract = self.w3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) tx_hash = contract.constructor().transact(transaction=None) tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash) contract_instance = self.w3.eth.contract( address=tx_receipt.contractAddress, abi=contract_abi) if isConcise: concise_instance = ConciseContract(contract_instance) return concise_instance return contract_instance
def test_conciscecontract_function_collision( web3, StringContract): contract = deploy(web3, StringContract, args=["blarg"]) def getValue(): assert 'getValue' in [ item['name'] for item in StringContract.abi if 'name' in item] setattr(ConciseContract, 'getValue', getValue) concise_contract = ConciseContract(contract) assert isinstance(concise_contract, ConciseContract) with pytest.raises(AttributeError, match=r'Namespace collision .* with ConciseContract API.'): concise_contract.getValue()