def parse_attributes(serialized_attributes: str or bytes): if len(serialized_attributes) == 0: return list() if isinstance(serialized_attributes, str): stream = StreamManager.get_stream( bytearray.fromhex(serialized_attributes)) elif isinstance(serialized_attributes, bytes): stream = StreamManager.get_stream(serialized_attributes) else: raise SDKException( ErrorCode.params_type_error( 'bytes or str parameter is required.')) reader = BinaryReader(stream) attributes_list = [] while True: try: attr_key = reader.read_var_bytes().decode('utf-8') attr_type = reader.read_var_bytes().decode('utf-8') attr_value = reader.read_var_bytes().decode('utf-8') attr = dict(Key=attr_key, Type=attr_type, Value=attr_value) attributes_list.append(attr) except SDKException as e: if 10000 < e.args[0] < 20000: break else: raise e return attributes_list
def parse_pub_keys(ont_id: str, raw_pub_keys: str or bytes) -> list: if isinstance(raw_pub_keys, str): stream = StreamManager.get_stream(bytearray.fromhex(raw_pub_keys)) elif isinstance(raw_pub_keys, bytes): stream = StreamManager.get_stream(raw_pub_keys) else: raise SDKException(ErrorCode.params_type_error('bytes or str parameter is required.')) reader = BinaryReader(stream) pub_keys = list() while True: try: kid = f'{ont_id}#keys-{reader.read_int32()}' bytes_key = reader.read_var_bytes() hex_pub_key = bytes_key.hex() if len(bytes_key) == 33: key_info = dict(PubKeyId=kid, Type=KeyType.ECDSA.name, Curve=Curve.P256.name, Value=hex_pub_key) else: key_type = KeyType.from_label(bytes_key[0]) curve = Curve.from_label(bytes_key[1]) key_info = dict(PubKeyId=kid, Type=key_type, Curve=curve, Value=hex_pub_key) pub_keys.append(key_info) except SDKException as e: if e.args[0] != 10001: raise e else: break return pub_keys
def __get_peer_pool_map(self, peer_pubkey=None): contract_address = bytearray.fromhex(self.CONTRACT_ADDRESS) contract_address.reverse() view = self.__sdk.rpc.get_storage(contract_address.hex(), self.GOVERNANCE_VIEW.encode().hex()) if view is None or view == '': return None stream = StreamManager.get_stream(bytearray.fromhex(view)) reader = BinaryReader(stream) governance_view = GovernanceView() governance_view.deserialize(reader) stream.close() stream2 = StreamManager.get_stream() writer = BinaryWriter(stream2) writer.write_int32(governance_view.view) view_bytes = stream2.to_bytes() peer_pool_bytes = self.PEER_POOL.encode('utf-8') key_bytes = peer_pool_bytes + a2b_hex(view_bytes) value = self.__sdk.rpc.get_storage(contract_address.hex(), key_bytes.hex()) if value is None or value == '': return None stream3 = StreamManager.get_stream(bytearray.fromhex(value)) reader2 = BinaryReader(stream3) length = reader2.read_int32() peer_pool_map = {} for _ in range(length): item = PeerPoolItem() item.deserialize(reader2) peer_pool_map[item.peer_pubkey] = item.to_json() if peer_pubkey is not None: if peer_pubkey not in peer_pool_map: return None return peer_pool_map[peer_pubkey] return peer_pool_map
async def get_ddo(ont_id): contract_address = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' \ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03' version = b'\x00' remote = 'http://dappnode1.ont.io:20336/' sdk = Ontology(rpc_address=remote) args = dict(ontid=ont_id.encode('utf-8')) invoke_code = build_vm.build_native_invoke_code(contract_address, version, 'getDDO', args) tx = Transaction(0, 0xd1, 0, 0, b'', invoke_code) response = await sdk.aio_rpc.send_raw_transaction_pre_exec(tx) serialized_ddo = response['Result'] if len(serialized_ddo) == 0: return dict() if isinstance(serialized_ddo, str): stream = StreamManager.get_stream(bytearray.fromhex(serialized_ddo)) elif isinstance(serialized_ddo, bytes): stream = StreamManager.get_stream(serialized_ddo) else: raise SDKException( ErrorCode.params_type_error('unexpected data type {}'.format( type(serialized_ddo)))) reader = BinaryReader(stream) try: public_key_bytes = reader.read_var_bytes() except SDKException: public_key_bytes = b'' try: attribute_bytes = reader.read_var_bytes() except SDKException: attribute_bytes = b'' try: recovery_bytes = reader.read_var_bytes() except SDKException: recovery_bytes = b'' if len(recovery_bytes) != 0: b58_recovery = Address(recovery_bytes).b58encode() else: b58_recovery = '' try: controller = reader.read_var_bytes().decode('utf-8') except SDKException: controller = '' try: recovery = reader.read_var_bytes().decode('utf-8') except SDKException: recovery = '' pub_keys = ontid.OntId.parse_pub_keys(ont_id, public_key_bytes) attribute_list = ontid.OntId.parse_attributes(attribute_bytes) return dict( id=ont_id, keys=pub_keys, ctrl=controller, attributes=attribute_list, recovery=recovery if recovery else b58_recovery, )
def test_read_var_int(self): value = 123 writer_stream = StreamManager.get_stream() writer = BinaryWriter(writer_stream) writer.write_var_int(value) reader_stream = StreamManager.get_stream(writer_stream.getbuffer()) reader = BinaryReader(reader_stream) self.assertEqual(reader.read_var_int(), value)
def push_bytes(data): ms = StreamManager.get_stream() writer = BinaryWriter(ms) if len(data) == 0: raise ValueError("push data error: data is null") if len(data) <= int.from_bytes(PUSHBYTES75, 'little') + 1 - int.from_bytes( PUSHBYTES1, 'little'): num = len(data) + int.from_bytes(PUSHBYTES1, 'little') - 1 writer.write_byte(num) elif len(data) < 0x100: writer.write_byte(PUSHDATA1) writer.write_uint8(len(data)) elif len(data) < 0x10000: writer.write_byte(PUSHDATA2) writer.write_uint16(len(data)) else: writer.write_byte(PUSHDATA4) writer.write_uint32(len(data)) writer.write_bytes(data) ms.flush() res = ms.to_bytes() StreamManager.release_stream(ms) res = bytes_reader(res) return res
def parse_ddo(ont_id: str, serialized_ddo: str or bytes) -> dict: """ This interface is used to deserialize a hexadecimal string into a DDO object in the from of dict. :param ont_id: the unique ID for identity. :param serialized_ddo: an serialized description object of ONT ID in form of str or bytes. :return: a description object of ONT ID in the from of dict. """ if len(serialized_ddo) == 0: return dict() if isinstance(serialized_ddo, str): stream = StreamManager.get_stream( bytearray.fromhex(serialized_ddo)) elif isinstance(serialized_ddo, bytes): stream = StreamManager.get_stream(serialized_ddo) else: raise SDKException( ErrorCode.params_type_error( 'bytes or str parameter is required.')) reader = BinaryReader(stream) try: public_key_bytes = reader.read_var_bytes() except SDKException: public_key_bytes = b'' try: attribute_bytes = reader.read_var_bytes() except SDKException: attribute_bytes = b'' try: recovery_bytes = reader.read_var_bytes() except SDKException: recovery_bytes = b'' if len(recovery_bytes) != 0: b58_recovery = Address(recovery_bytes).b58encode() else: b58_recovery = '' pub_keys = OntId.parse_pub_keys(ont_id, public_key_bytes) attribute_list = OntId.parse_attributes(attribute_bytes) ddo = dict(Owners=pub_keys, Attributes=attribute_list, Recovery=b58_recovery, OntId=ont_id) return ddo
def get_public_key_serialize(self): stream = StreamManager.get_stream() writer = BinaryWriter(stream) if self.__key_type == KeyType.ECDSA: writer.write_var_bytes(self.__public_key) else: raise SDKException(ErrorCode.unknown_asymmetric_key_type) stream.flush() bytes_stream = stream.hexlify() StreamManager.release_stream(stream) return bytes_stream
def get_param_info(program: bytes): ms = StreamManager.get_stream(program) reader = BinaryReader(ms) param_info = [] while True: try: res = ProgramBuilder.read_bytes(reader) except SDKException: break param_info.append(res) return param_info
def op_code_to_int(op_code: str): if op_code.lower() == '4f': return -1 elif op_code == '00': return 0 elif 80 < int(op_code, base=16) < 103: return int(op_code, base=16) - 80 else: op_code = bytearray.fromhex(op_code) stream = StreamManager.get_stream(op_code) reader = BinaryReader(stream) op_code = bytearray(reader.read_var_bytes()) return ContractDataParser.neo_bytearray_to_big_int(op_code)
def serialize(self, is_hex: bool = False) -> bytes or str: ms = StreamManager.get_stream() writer = BinaryWriter(ms) writer.write_bytes(self.serialize_unsigned(is_str=False)) writer.write_var_int(len(self.sig_list)) for sig in self.sig_list: writer.write_bytes(sig.serialize()) ms.flush() bytes_tx = ms.to_bytes() StreamManager.release_stream(ms) if is_hex: return bytes_tx.hex() else: return bytes_tx
def get_total_stake(self, address: str): contract_address = bytearray.fromhex(self.CONTRACT_ADDRESS) contract_address.reverse() total_bytes = self.TOTAL_STAKE.encode('utf-8') address_bytes = Address.b58decode(address).to_bytes() key = total_bytes + address_bytes res = self.__sdk.rpc.get_storage(contract_address.hex(), key.hex()) if res is None or res == '': return None stream = StreamManager.get_stream(bytearray.fromhex(res)) reader = BinaryReader(stream) total_stake = TotalStake() total_stake.deserialize(reader) stream.close() return total_stake
def get_peer_attributes(self, peer_pubkey: str): contract_address = bytearray.fromhex(self.CONTRACT_ADDRESS) contract_address.reverse() peer_attributes = self.PEER_ATTRIBUTES.encode('utf-8') peer_pubkey_bytes = a2b_hex(peer_pubkey.encode()) key = peer_attributes + peer_pubkey_bytes res = self.__sdk.rpc.get_storage(contract_address.hex(), key.hex()) if res is None or res == '': return None peer_attributes = PeerAttributes() stream = StreamManager.get_stream(bytearray.fromhex(res)) reader = BinaryReader(stream) peer_attributes.deserialize(reader) stream.close() return peer_attributes.to_json()
def get_authorize_info(self, peer_pubkey: str, addr: Address): contract_address = bytearray.fromhex(self.CONTRACT_ADDRESS) contract_address.reverse() peer_pubkey_prefix = bytearray.fromhex(peer_pubkey) address_bytes = addr.to_bytes() authorize_info_pool = self.AUTHORIZE_INFO_POOL.encode() key = authorize_info_pool + peer_pubkey_prefix + address_bytes res = self.__sdk.rpc.get_storage(contract_address.hex(), key.hex()) if res is None or res == '': return None stream = StreamManager.get_stream(bytearray.fromhex(res)) reader = BinaryReader(stream) authorize_info = AuthorizeInfo() authorize_info.deserialize(reader) return authorize_info.to_json()
def get_split_fee_address(self, address: str): contract_address = bytearray.fromhex(self.CONTRACT_ADDRESS) contract_address.reverse() split_fee_address_bytes = self.SPLIT_FEE_ADDRESS.encode() address_bytes = Address.b58decode(address).to_bytes() key = split_fee_address_bytes + address_bytes res = self.__sdk.rpc.get_storage(contract_address.hex(), key.hex()) if res is None or res == '': return None split_fee_address = SplitFeeAddress() stream = StreamManager.get_stream(bytearray.fromhex(res)) reader = BinaryReader(stream) split_fee_address.deserialize(reader) stream.close() return split_fee_address.to_json()
def serialize_unsigned(self) -> bytes or str: ms = StreamManager.get_stream() writer = BinaryWriter(ms) writer.write_uint8(self.version) writer.write_uint8(self.tx_type) writer.write_uint32(self.nonce) writer.write_uint64(self.gas_price) writer.write_uint64(self.gas_limit) writer.write_bytes(self.payer) self.serialize_exclusive_data(writer) if self.payload is not None and len(self.payload) != 0: writer.write_var_bytes(bytes(self.payload)) writer.write_var_int(len(self.attributes)) ms.flush() hex_bytes = ms.to_bytes() StreamManager.release_stream(ms) return hex_bytes
def serialize(self) -> bytes: invoke_script = ProgramBuilder.program_from_params(self.__sig_data) if len(self.public_keys) == 0: raise SDKException(ErrorCode.other_error('Public key in sig is empty.')) if len(self.public_keys) == 1: verification_script = ProgramBuilder.program_from_pubkey(self.public_keys[0]) else: verification_script = ProgramBuilder.program_from_multi_pubkey(self.m, self.public_keys) ms = StreamManager.get_stream() writer = BinaryWriter(ms) writer.write_var_bytes(invoke_script) writer.write_var_bytes(verification_script) ms.flush() res = ms.to_bytes() res = bytes_reader(res) StreamManager.release_stream(ms) return res
def deserialize_from(bytes_tx: bytes): ms = StreamManager.get_stream(bytes_tx) reader = BinaryReader(ms) tx = Transaction() tx.version = reader.read_uint8() tx.tx_type = reader.read_uint8() tx.nonce = reader.read_uint32() tx.gas_price = reader.read_uint64() tx.gas_limit = reader.read_uint64() tx.payer = reader.read_bytes(20) tx.payload = reader.read_var_bytes() attribute_len = reader.read_var_int() if attribute_len is 0: tx.attributes = bytearray() sig_len = reader.read_var_int() tx.sig_list = list() for _ in range(0, sig_len): tx.sig_list.append(Sig.deserialize(reader)) return tx
def get_program_info(program: bytes) -> ProgramInfo: length = len(program) end = program[length - 1] temp = program[:length - 1] ms = StreamManager.get_stream(temp) reader = BinaryReader(ms) info = ProgramInfo() if end == int.from_bytes(CHECKSIG, 'little'): pub_keys = ProgramBuilder.read_bytes(reader) info.set_pubkey([pub_keys]) info.set_m(1) elif end == int.from_bytes(CHECKMULTISIG, 'little'): length = program[len(program) - 2] - int.from_bytes(PUSH1, 'little') + 1 m = reader.read_byte() - int.from_bytes(PUSH1, 'little') + 1 pub = [] for _ in range(length): pub.append(reader.read_var_bytes()) info.set_pubkey(pub) info.set_m(m) return info
def deserialize_hex(item_serialize: str): stream = StreamManager.get_stream(bytearray.fromhex(item_serialize)) reader = BinaryReader(stream) return deserialize_stack_item(reader)
def to_dict(item_serialize: str) -> dict: stream = StreamManager.get_stream(bytearray.fromhex(item_serialize)) reader = BinaryReader(stream) return ContractDataParser.__deserialize_stack_item(reader)
def deserialize_from(sig_bytes: bytes): ms = StreamManager.get_stream(sig_bytes) reader = BinaryReader(ms) return Sig.deserialize(reader)