def to_b58_address(hex_address: str) -> str: try: bytes_address = binascii.a2b_hex(hex_address) except binascii.Error as e: raise SDKException(ErrorCode.other_error(e.args[0])) address = Address(bytes_address) return address.b58encode()
def to_b58_address(hex_address: str) -> str: try: bytes_address = bytes.fromhex(hex_address) except ValueError as e: raise SDKException(ErrorCode.other_error(e.args[0])) address = Address(bytes_address) return address.b58encode()
class PeerPoolItem(object): def __init__(self): self.index = 0 self.peer_pubkey = '' self.address = None self.status = 0 self.init_pos = 0 self.total_pos = 0 def deserialize(self, reader: BinaryReader): self.index = reader.read_int32() self.peer_pubkey = a2b_hex(reader.read_var_str()).hex() self.address = Address(reader.read_bytes(20)) self.status = reader.read_byte() self.init_pos = reader.read_int64() self.total_pos = reader.read_int64() def to_json(self): item = {} item["index"] = self.index item["peer_pubkey"] = self.peer_pubkey item["address"] = self.address.b58encode() item["status"] = self.status item["init_pos"] = self.init_pos item["total_pos"] = self.total_pos return item
class AuthorizeInfo(object): def __init__(self): self.peer_pubkey = '' self.address = None self.consensus_pos = 0 self.freeze_pos = 0 self.new_pos = 0 self.withdraw_pos = 0 self.withdraw_freeze_pos = 0 self.withdraw_unfreeze_pos = 0 def deserialize(self, reader: BinaryReader): self.peer_pubkey = a2b_hex(reader.read_var_str()).hex() self.address = Address(reader.read_bytes(20)) self.consensus_pos = reader.read_int64() self.freeze_pos = reader.read_int64() self.new_pos = reader.read_int64() self.withdraw_pos = reader.read_int64() self.withdraw_freeze_pos = reader.read_int64() self.withdraw_unfreeze_pos = reader.read_int64() def to_json(self): map = dict() map["peer_pubkey"] = self.peer_pubkey map["address"] = self.address.b58encode() map["consensus_pos"] = self.consensus_pos map["freeze_pos"] = self.freeze_pos map["new_pos"] = self.new_pos map["withdraw_pos"] = self.withdraw_pos map["withdraw_freeze_pos"] = self.withdraw_freeze_pos map["withdraw_unfreeze_pos"] = self.withdraw_unfreeze_pos return map
def test_b58decode(self): length = 20 rand_code = utils.get_random_bytes(length) address = Address(rand_code) b58_address = address.b58encode() zero = Address.b58decode(b58_address).to_bytes() self.assertEqual(rand_code, zero) decode_address = Address.b58decode(b58_address).to_bytes() self.assertEqual(rand_code, decode_address)
def runtime_check_witness(self, config: Config, engine: ExecutionEngine): data = PushData.pop_bytearray(engine) if len(data) == 20: address = Address(data) l = config.get_signature_addresses() if address.b58encode() in l: PushData.push_data(engine, BoolItem(True)) else: PushData.push_data(engine, BoolItem(False))
def test_b58decode(self): length = 20 rand_code = util.get_random_bytes(length) address = Address(rand_code) b58_address = address.b58encode() zero = Address.b58decode(b58_address) self.assertEqual(rand_code, zero) decode_address = Address.b58decode(b58_address, is_bytes=False) self.assertTrue(isinstance(decode_address, Address)) self.assertEqual(rand_code, decode_address.to_array())
def test_testAddress(self): payerAcct = adminAcct param_list = [] param_list.append("testAddress".encode()) param_list1 = [] param_list.append(param_list1) # print("***** getExplodePoint", param_list) res = self.test_invokeRead(payerAcct, param_list) print("res === testAddress", res) account = Address(binascii.a2b_hex(res)) account = account.b58encode() print("res === testAddress", account)
class SplitFeeAddress(object): def __init__(self): self.address = None self.amount = 0 def deserialize(self, reader: BinaryReader): self.address = Address(reader.read_bytes(20)) self.amount = reader.read_int64() def to_json(self): map = dict() map["address"] = self.address.b58encode() map["amount"] = self.amount return map
def test_handleEvent(self, action, hash): res = sdk.rpc.get_smart_contract_event_by_tx_hash(hash) if action == "setOddsTable": events = res["Notify"] # print("buyPaper-res-events is ", events) notifyContents = [] for event in events: notifyContent = [] if event["ContractAddress"] == ContractAddress: first = (bytearray.fromhex(event["States"][0])).decode('utf-8') notifyContent.append(first) notifyContents.append(notifyContent) print("setOddsTable-res-events is : ", notifyContents) elif action == "setLuckyToOngRate": events = res["Notify"] # print("buyPaper-res-events is ", events) notifyContents = [] for event in events: notifyContent = [] if event["ContractAddress"] == ContractAddress: first = (bytearray.fromhex(event["States"][0])).decode('utf-8') notifyContent.append(first) if first == "setRate": num = event["States"][1] if not num: num = "0" num = bytearray.fromhex(num) num.reverse() num = int(num.hex(), 16) notifyContent.append(num) num = event["States"][2] if not num: num = "0" num = bytearray.fromhex(num) num.reverse() num = int(num.hex(), 16) notifyContent.append(num) notifyContents.append(notifyContent) print("setLuckyToOngRate-res-events is : ", notifyContents) elif action == "startNewRound": events = res["Notify"] notifyContents = [] for event in events: notifyContent = [] if event["ContractAddress"] == ContractAddress: first = (bytearray.fromhex(event["States"][0])).decode('utf-8') notifyContent.append(first) if first == "startNewRound": roundNumber = event["States"][1] if not roundNumber: num = "0" roundNumber = bytearray.fromhex(roundNumber) roundNumber.reverse() roundNumber = int(roundNumber.hex(), 16) notifyContent.append(roundNumber) timeStamp = str(event["States"][2]) if not timeStamp: timeStamp = "0" timeStamp = bytearray.fromhex(timeStamp) timeStamp.reverse() timeStamp = int(timeStamp.hex(), 16) dateTime = datetime.utcfromtimestamp(timeStamp).strftime('%Y-%m-%d %H:%M:%S') notifyContent.append(dateTime) hashHexString = str(event["States"][3]) notifyContent.append(hashHexString) notifyContents.append(notifyContent) print("startNewRound-res-events is : ", notifyContents) elif action == "bet": events = res["Notify"] notifyContents = [] i = 1 for event in events: notifyContent = [] if event["ContractAddress"] == ContractAddress: first = (bytearray.fromhex(event["States"][0])).decode('utf-8') notifyContent.append(first) if first == "bet": roundNumber = event["States"][1] if not roundNumber: num = "0" roundNumber = bytearray.fromhex(roundNumber) roundNumber.reverse() roundNumber = int(roundNumber.hex(), 16) notifyContent.append(roundNumber) account = Address(binascii.a2b_hex(event["States"][2])) account = account.b58encode() notifyContent.append(account) num = event["States"][3] if not num: num = "0" num = bytearray.fromhex(num) num.reverse() num = int(num.hex(), 16) notifyContent.append(num) notifyContents.append(notifyContent) print("bet-res-events is : ", notifyContents) elif action == "endCurrentRound": res = sdk.rpc.get_smart_contract_event_by_tx_hash(hash) print("endCurrentRound-res is ", res) events = res["Notify"] notifyContents = [] i = 1 # print("events === ", events) for event in events: notifyContent = [] if event["ContractAddress"] == ContractAddress: first = (bytearray.fromhex(event["States"][0])).decode('utf-8') if first == "endCurrentRound": notifyContent.append(first) roundNumber = event["States"][1] if not roundNumber: num = "0" roundNumber = bytearray.fromhex(roundNumber) roundNumber.reverse() roundNumber = int(roundNumber.hex(), 16) notifyContent.append(roundNumber) explodePoint = event["States"][2] if not explodePoint: explodePoint = "0" explodePoint = bytearray.fromhex(explodePoint) explodePoint.reverse() explodePoint = int(explodePoint.hex(), 16) notifyContent.append(explodePoint) salt = event["States"][3] if not salt: salt = "0" salt = bytearray.fromhex(salt) salt.reverse() salt = int(salt.hex(), 16) notifyContent.append(salt) effectiveEscapeAcctPointOddsProfitList = event["States"][4] notify1 = [] for effectiveEscapeAcctPointOddsProfit in effectiveEscapeAcctPointOddsProfitList: notify2 = [] account = Address(binascii.a2b_hex(effectiveEscapeAcctPointOddsProfit[0])) account = account.b58encode() notify2.append(account) escapePoint = effectiveEscapeAcctPointOddsProfit[1] if not escapePoint: escapePoint = "0" escapePoint = bytearray.fromhex(escapePoint) escapePoint.reverse() escapePoint = int(escapePoint.hex(), 16) notify2.append(escapePoint) # odds = effectiveEscapeAcctPointOddsProfit[2] # if not odds: # odds = "0" # odds = bytearray.fromhex(odds) # odds.reverse() # odds = int(odds.hex(), 16) # notify2.append(odds) profit = effectiveEscapeAcctPointOddsProfit[2] if not profit: profit = "0" profit = bytearray.fromhex(profit) profit.reverse() profit = int(profit.hex(), 16) notify2.append(profit) notify1.append(notify2) notifyContent.append(notify1) # print("endCurrentRound-res-event is : ", notifyContent) elif first == "Error": errorCode = event["States"][1] if not errorCode: errorCode = "0" errorCode = bytearray.fromhex(errorCode) errorCode.reverse() errorCode = int(errorCode.hex(), 16) notifyContent.append(errorCode) notifyContents.append(notifyContent) print("endCurrentRound-res-events is : ", notifyContents) return True
def parse_ddo(ont_id: str, ddo: str) -> dict: if ddo == "": return dict() ms = StreamManager.GetStream(a2b_hex(ddo)) reader = BinaryReader(ms) try: publickey_bytes = reader.read_var_bytes() except Exception as e: raise e try: attribute_bytes = reader.read_var_bytes() except Exception as e: attribute_bytes = bytearray() try: recovery_bytes = reader.read_var_bytes() except Exception as e: recovery_bytes = bytearray() pubKey_list = [] if len(publickey_bytes) != 0: ms = StreamManager.GetStream(publickey_bytes) reader2 = BinaryReader(ms) while True: try: index = reader2.read_int32() d = {} d['PubKeyId'] = ont_id + "#keys-" + str(index) pubkey = reader2.read_var_bytes() if len(pubkey) == 33: d["Type"] = KeyType.ECDSA.name d["Curve"] = Curve.P256.name d["Value"] = pubkey.hex() else: d["Type"] = KeyType.from_label(pubkey[0]) d["Curve"] = Curve.from_label(pubkey[1]) d["Value"] = pubkey.hex() pubKey_list.append(d) except Exception as e: break attribute_list = [] if len(attribute_bytes) != 0: ms = StreamManager.GetStream(attribute_bytes) reader2 = BinaryReader(ms) while True: try: d = {} key = reader2.read_var_bytes() if len(key) == 0: break d["Key"] = str(key, 'utf-8') d["Type"] = str(reader2.read_var_bytes(), 'utf-8') d["Value"] = str(reader2.read_var_bytes(), 'utf-8') attribute_list.append(d) except Exception as e: break d2 = {} d2["Owners"] = pubKey_list d2["Attributes"] = attribute_list if len(recovery_bytes) != 0: addr = Address(recovery_bytes) d2["Recovery"] = addr.b58encode() d2["OntId"] = ont_id return d2
def invoke(sdk, m, function_name=None): func_maps = {} for i in dict(m["function"]).values(): if function_name is not None: if i["function_name"] not in function_name: continue func_map = {} param_list = [] func_map["function_name"] = i["function_name"] func_map["pre_exec"] = i["pre_exec"] try: if type(i["function_param"]) is dict: for value in dict(i["function_param"]).values(): if type(value) is list: p_temp = [] for v in list(value): p_temp.append(v) param_list.append(p_temp) else: param_list.append(value) elif type(i["function_param"]) is list: temp_list = [] for para in list(i["function_param"]): if type(para) is dict: temp_list2 = [] for para2 in dict(para).values(): temp_list2.append(para2) temp_list.append(temp_list2) # if type(para) is : else: temp_list.append(para) param_list.append(temp_list) func_map["param_list"] = param_list except Exception as e: pass if not i["pre_exec"]: try: func_map["signers"] = i["signers"] except AttributeError as e: func_map["signers"] = None func_maps[i["function_name"]] = func_map with open(str(m["abi_path"]), "r") as f: abi = json.loads(f.read(), object_hook=lambda d: namedtuple('X', d.keys()) (*d.values())) abi_info = AbiInfo(abi.hash, abi.entrypoint, abi.functions, abi.events) # print("abi_info is ", abi_info.hash, abi_info.entrypoint, abi_info.events, abi_info.functions) tmp = str(abi.hash)[2:] # print("tmp is ", tmp, type(tmp)) contract_address = bytearray.fromhex(tmp) # print("contract_address is ", contract_address, type(contract_address)) m["contract_address"] = contract_address.hex() contract_address.reverse() sdk.wallet_manager.open_wallet(m["wallet_file_path"]) payer = sdk.wallet_manager.get_account(m["payer_address"], m["payer_password"]) func_l = [] no = 0 for func_map in func_maps.values(): if function_name is not None: if func_map["function_name"] not in function_name: # params = BuildParams.create_code_params_script(function_name) continue func = abi_info.get_function(func_map["function_name"]) # print('func is ', func) if func is not None: func_map["return_type"] = func.return_type else: func_map["return_type"] = "" func = AbiFunction(func_map["function_name"], func_map["return_type"], func_map["param_list"]) #print("func_map is ", func_map) #print("func is ", func) # print("func = "+str(func.name)+" -- "+str(func.parameters[0:])+" -- " +str(func.return_type)) no = no + 1 l = [] l.append(no) l.append(func_map["function_name"]) l.append(func_map["pre_exec"]) # 用来放参数 # print("func_map is ", func_map) # print("func is ", func) temp_l, params = convert_params(func, func_map) print("********", params) l.append(temp_l[:len(temp_l) - 1]) if params is None: l.append("failed") func_l.append(l) continue try: print("") print("invoking, please waiting ...") print("method: " + func_map["function_name"]) if func_map["pre_exec"]: res = send_transaction(sdk, contract_address, None, None, 0, 0, params, True) # print("res in pre_exec part :", res) if res["error"] != 0: print(res["desc"]) l.append(res["desc"]) else: # print('**** res **** is ', res) # print("######## res[result][Result] is ",res["result"]["Result"], type(res["result"]["Result"])) if res["result"]["Result"] is None or res["result"][ "Result"] == "": # print("res:", res["result"]["Result"]) l.append("") else: if func_map["return_type"] == "Integer": value = bytearray.fromhex( res["result"]["Result"]) value.reverse() print("res:", int(value.hex(), 16)) l.append(int(value.hex(), 16)) elif func_map["return_type"] == "ByteArray": # print("res:", (bytearray.fromhex(res["result"]["Result"]))) print("res:", res["result"]["Result"]) l.append(res["result"]["Result"]) elif func_map["return_type"] == "": print("res:", res["result"]["Result"]) l.append(res["result"]["Result"]) elif func_map["return_type"] == "IntegerArray": # print(" returntype = IntegerArray ") print("res For IntegerArray is ", res["result"]["Result"]) returnedList = res["result"]["Result"] intReturnList = [] for element in returnedList: if not element: element = "00" value = bytearray.fromhex(element) value.reverse() intValue = int(value.hex(), 16) intReturnList.append(intValue) print("res: ", intReturnList) l.append(intReturnList) elif func_map["return_type"] == "ByetArrayArray": print(" returntype = ByteArrayArray ") print("res For ByetArrayArray is ", res["result"]["Result"]) returnedList = res["result"]["Result"] ByteArrayReturnList = [] for element in returnedList: # Address.b58decode(func_map["param_list"][i], False).to_array() # ByteArrayValue = (bytearray.fromhex(element)) # str1 = "7575526bc066a3acc6abb134119cd6d4a9041969" # address1=Address(binascii.a2b_hex(str1)) address1 = Address( binascii.a2b_hex(element)) ByteArrayValue = address1.b58encode() ByteArrayReturnList.append(ByteArrayValue) print("res: ", ByteArrayReturnList) l.append(ByteArrayReturnList) else: print("res:", (bytearray.fromhex( res["result"]["Result"])).decode('utf-8')) l.append((bytearray.fromhex( res["result"]["Result"])).decode('utf-8')) else: txhash, err = handle_tx(contract_address, func_map, params, payer, m, sdk) if txhash == "": l.append(err) else: for i in range(10): time2.sleep(1) event = sdk.rpc.get_smart_contract_event_by_tx_hash( txhash) if event is not None: print("txhash:", txhash) print("event:", event) break l.append(txhash) except Exception as e: print("Error:", e) l.append(e) func_l.append(l) save_file(m, "", func_l)