def from_order(cls, order: Order) -> "OrderORM": return cls( exchange_address=order.exchange_address, maker_address=order.maker_address, taker_address=order.taker_address, maker_token=order.maker_token, taker_token=order.taker_token, fee_recipient=order.fee_recipient, maker_token_amount=order.maker_token_amount, taker_token_amount=order.taker_token_amount, filled_maker_token_amount=order.filled_maker_token_amount, filled_taker_token_amount=order.filled_taker_token_amount, cancelled_maker_token_amount=order.cancelled_maker_token_amount, cancelled_taker_token_amount=order.cancelled_taker_token_amount, price=order.price, maker_fee=order.maker_fee, taker_fee=order.taker_fee, expiration_timestamp_in_sec=order.expiration_timestamp_in_sec, salt=order.salt, v=order.v, # remove 0x from r, s and msg_hash to keep backwards compatibility: r=remove_0x_prefix(order.r.hex()), s=remove_0x_prefix(order.s.hex()), msg_hash=remove_0x_prefix(order.hash().hex()), )
def delete_orders_by_hash(self, order_hashes: Sequence[hexbytes.HexBytes]) -> None: for order_hash in order_hashes: self.session.query(OrderORM).filter_by( # remove 0x to keep backwards compatibility msg_hash=remove_0x_prefix(order_hash.hex()) ).delete(synchronize_session=False) self.session.commit()
def add_order(self, order: Order) -> None: order_orm = self.session.query(OrderORM).get( # remove 0x to keep backwards compatibility remove_0x_prefix(HexStr(order.hash().hex()))) if order_orm is None: order_orm = OrderORM.from_order(order) self.session.add(order_orm) self.session.commit()
def get_order_by_hash(self, order_hash: hexbytes.HexBytes) -> Optional[Order]: # remove 0x to keep backwards compatibility order_orm = self.session.query(OrderORM).get( remove_0x_prefix(HexStr(order_hash.hex()))) if order_orm is None: return None return order_orm.to_order()
def is_valid_token(tok): try: assert tok is not None assert type(tok) == str assert len(remove_0x_prefix(tok)) == 64 assert re.match(HEX_PATTERN, tok) is not None return True except AssertionError: return False
def asset2str(asset: int) -> str: """ convert asset id from int to hex string without 0x :param asset: asset id in int format :return: asset id in hex string format .. code-block:: python >>> from asimov import Asset >>> Asset.asset2str(4294967297) '000000000000000100000001' """ return remove_0x_prefix(hex(asset)).zfill(24)
def order_cancelled( self, order_hash: hexbytes.HexBytes, cancelled_maker_token_amount: int, cancelled_taker_token_amount: int, ) -> None: order_orm = ( self.session.query(OrderORM) # remove 0x to keep backwards compatibility .filter_by(msg_hash=remove_0x_prefix(order_hash.hex())).first() ) if order_orm is not None: order_orm.cancelled_maker_token_amount += cancelled_maker_token_amount order_orm.cancelled_taker_token_amount += cancelled_taker_token_amount if order_orm.to_order().is_filled(): self.session.delete(order_orm) self.session.commit()
def read(self, func_name, args=None): """ call a view/pure function in the contract and return the execution result :param func_name: function name :param args: function arguments :return: the return value of the readonly function .. code-block:: python >>> from asimov import Contract, Node, AsimovSolc >>> node = Node("http://seed.asimov.tech") >>> contract = Contract(node, c=AsimovSolc.compile("/path/to/my/sources/example.sol")['Example']) >>> contract.read("readonly function name") """ return self.node._call_readonly_function( contract_address=self.address, # pylint: disable=no-value-for-parameter data=remove_0x_prefix(self.encode_tx_data(func_name, args=args)), func_name=func_name, abi=self.abi_json_str)
def getDelegateReward(self, from_address, node_ids=[]): node_id_bytes = [bytes.fromhex(node_id) for node_id in node_ids] data = [ rlp.encode(int(5100)), rlp.encode(bytes.fromhex(remove_0x_prefix(from_address))), rlp.encode(node_id_bytes) ] data = rlp.encode(data) raw_data = call_obj(self, from_address, self.web3.delegateRewardAddress, data) receive = json.loads(str(raw_data, encoding="ISO-8859-1")) try: raw_data_dict = receive["Ret"] result = [] for d in raw_data_dict: d["reward"] = int(d["reward"], 16) result.append(d) receive["Ret"] = result except: ... return receive
def ecrecover(self, block_identifier): block = self.getBlock(block_identifier) extra = block.proofOfAuthorityData[0:32] sign = block.proofOfAuthorityData[32:] raw_data = [ bytes.fromhex(remove_0x_prefix(block.parentHash.hex())), bytes.fromhex(remove_0x_prefix(block.miner)), bytes.fromhex(remove_0x_prefix(block.stateRoot.hex())), bytes.fromhex(remove_0x_prefix(block.transactionsRoot.hex())), bytes.fromhex(remove_0x_prefix(block.receiptsRoot.hex())), bytes.fromhex(remove_0x_prefix(block.logsBloom.hex())), block.number, block.gasLimit, block.gasUsed, block.timestamp, extra, bytes.fromhex(remove_0x_prefix(block.nonce)) ] message_hash = sha3.keccak_256(rlp.encode(raw_data)).digest() hash_bytes = HexBytes(message_hash) signature_bytes = HexBytes(sign) signature_bytes_standard = to_standard_signature_bytes(signature_bytes) signature_obj = self.account._keys.Signature( signature_bytes=signature_bytes_standard) return remove_0x_prefix( signature_obj.recover_public_key_from_msg_hash( hash_bytes).to_hex())
def test_remove_0x_prefix_rejects_non_text_types(value): with pytest.raises(TypeError): remove_0x_prefix(value)
def test_remove_0x_prefix(value, expected): actual = remove_0x_prefix(value) assert actual == expected
def register_ddo(metadata, account, providers, auth_service, additional_service_descriptors, royalties=None, cap=None, mint=0): keeper = keeper_instance() metadata_api = Metadata('http://172.17.0.1:5000') ddo = DDO() ddo_service_endpoint = metadata_api.get_service_endpoint() metadata_service_desc = ServiceDescriptor.metadata_service_descriptor( metadata, ddo_service_endpoint) authorization_service_attributes = { "main": { "service": auth_service, "publicKey": "0xd7" } } service_descriptors = [ ServiceDescriptor.authorization_service_descriptor( authorization_service_attributes, 'http://localhost:12001') ] service_descriptors += [metadata_service_desc] service_descriptors += additional_service_descriptors services = ServiceFactory.build_services(service_descriptors) checksums = dict() for service in services: try: checksums[str(service.index)] = checksum(service.main) except Exception as e: pass # Adding proof to the ddo. ddo.add_proof(checksums, account) did_seed = checksum(ddo.proof['checksum']) asset_id = keeper.did_registry.hash_did(did_seed, account.address) ddo._did = DID.did(asset_id) did = ddo._did for service in services: if service.type == ServiceTypes.ASSET_ACCESS or service.type == ServiceTypes.NFT_ACCESS or service.type == ServiceTypes.ASSET_ACCESS_PROOF: access_service = ServiceFactory.complete_access_service( did, service.service_endpoint, service.attributes, keeper.access_template.address, keeper.escrow_payment_condition.address, service.type) ddo.add_service(access_service) elif service.type == ServiceTypes.CLOUD_COMPUTE: compute_service = ServiceFactory.complete_compute_service( did, service.service_endpoint, service.attributes, keeper.compute_execution_condition.address, keeper.escrow_payment_condition.address) ddo.add_service(compute_service) elif service.type == ServiceTypes.NFT_SALES: nft_sales_service = ServiceFactory.complete_nft_sales_service( did, service.service_endpoint, service.attributes, keeper.nft_sales_template.address, keeper.escrow_payment_condition.address, service.type) ddo.add_service(nft_sales_service) else: ddo.add_service(service) ddo.proof['signatureValue'] = keeper.sign_hash(did_to_id_bytes(did), account) ddo.add_public_key(did, account.address) ddo.add_authentication(did, PUBLIC_KEY_TYPE_RSA) try: _oldddo = metadata_api.get_asset_ddo(ddo.did) if _oldddo: metadata_api.retire_asset_ddo(ddo.did) except ValueError: pass if 'files' in metadata['main']: if auth_service == ServiceAuthorizationTypes.SECRET_STORE: encrypted_files = do_secret_store_encrypt( remove_0x_prefix(ddo.asset_id), json.dumps(metadata['main']['files']), account, get_config()) elif auth_service == ServiceAuthorizationTypes.PSK_RSA: encrypted_files, public_key = rsa_encryption_from_file( json.dumps(metadata['main']['files']), get_rsa_public_key_file()) else: encrypted_files, public_key = ecdsa_encryption_from_file( json.dumps(metadata['main']['files']), get_provider_key_file(), get_provider_password()) _files = metadata['main']['files'] # only assign if the encryption worked if encrypted_files: index = 0 for file in metadata['main']['files']: file['index'] = index index = index + 1 del file['url'] metadata['encryptedFiles'] = encrypted_files ddo_with_did = DDO(did, json_text=ddo.as_text().replace('/{did}', '/' + did)) ddo_service_endpoint = ddo_service_endpoint.replace('/{did}', '/' + did) if mint > 0 or royalties is not None or cap is not None: keeper.did_registry.register_mintable_did( did_seed, checksum=web3().toBytes(hexstr=ddo.asset_id), url=ddo_service_endpoint, cap=cap, royalties=royalties, account=account, providers=providers) if mint > 0: keeper.did_registry.mint(ddo.asset_id, mint, account=account) else: keeper_instance().did_registry.register( did_seed, checksum=web3().toBytes(hexstr=ddo.asset_id), url=ddo_service_endpoint, account=account, providers=providers) metadata_api.publish_asset_ddo(ddo_with_did) return ddo_with_did