def user_transaction_sell_list(request): user_id = request.POST.get('user_id') max_item_count = request.POST.get("page_max_items") page_id = request.POST.get("page_id") if max_item_count is None or page_id is None: max_item_count = page_id = None else: max_item_count = int(max_item_count) page_id = int(page_id) if max_item_count < 1 or page_id < 0: max_item_count = page_id = None contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() sell_res = client.call(contract_address, contract_abi, "get_transaction_sell_list", [user_id]) transaction_sell_list = [] transaction_sell_count = 0 for transaction_id in sell_res[0]: res = client.call(contract_address, contract_abi, "get_transaction_info", [transaction_id]) transaction_info = { "user_id_sell": res[1], "user_id_buy": res[2], "desc": res[3], "commodity_id": res[4], "price": res[5], "state": res[6], "id": transaction_id, } ret_code = 0 if transaction_info["state"] != -999 else -1 if ret_code == 0: transaction_sell_list.append(transaction_info) transaction_sell_count += 1 client.finish() if max_item_count is None: page_num = 1 if len(transaction_sell_list) > 0 else 0 else: page_num = (len(transaction_sell_list) + max_item_count - 1) // max_item_count transaction_sell_list = transaction_sell_list[page_id * max_item_count:(page_id + 1) * max_item_count] return JsonResponse({ "transaction_list": transaction_sell_list, "page_num": page_num, })
def user_commodity_list(request): user_id = request.POST.get('user_id') max_item_count = request.POST.get("page_max_items") page_id = request.POST.get("page_id") if max_item_count is None or page_id is None: max_item_count = page_id = None else: max_item_count = int(max_item_count) page_id = int(page_id) if max_item_count < 1 or page_id < 0: max_item_count = page_id = None contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "get_commodity_list", [user_id]) commodity_id_list, commodity_count = res commodity_list = [] for commodity_id in commodity_id_list: commodity_info = client.call(contract_address, contract_abi, "get_commodity_info", [commodity_id]) commodity_info = { "owner": commodity_info[0], "name": commodity_info[1], "image": commodity_info[2], "desc": commodity_info[3], "price": commodity_info[4], "state": commodity_info[5], "id": commodity_info[6], "type": commodity_info[7], } if commodity_info["state"] != -999: commodity_list.append(commodity_info) client.finish() if max_item_count is None: page_num = 1 if len(commodity_list) > 0 else 0 else: page_num = (len(commodity_list) + max_item_count - 1) // max_item_count commodity_list = commodity_list[page_id * max_item_count:(page_id + 1) * max_item_count] return JsonResponse({ "commodity_list": commodity_list, "page_num": page_num, })
def fisco_add_data_demo(): try: client = BcosClient() print(client.getinfo()) abi_file = os.path.join(settings.SITE_ROOT, "contracts", "HelloWorld.abi") data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi # 发送交易,调用一个改写数据的接口 print( "\n>>sendRawTransaction:----------------------------------------------------" ) to_address = '0x548fd1e8af9ca9131c04ab7e1031579f6498ddaf' # use new deploy address args = ["xy1211ddd"] receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "set", args) print("receipt:", receipt) # 解析receipt里的log print( "\n>>parse receipt and transaction:--------------------------------------" ) tx_hash = receipt['transactionHash'] print("transaction hash: ", tx_hash) log_result = data_parser.parse_event_logs(receipt["logs"]) i = 0 for log in log_result: if 'eventname' in log: i = i + 1 print("{}): log name: {} , data: {}".format( i, log['eventname'], log['eventdata'])) # 获取对应的交易数据,解析出调用方法名和参数 tx_response = client.getTransactionByHash(tx_hash) input_result = data_parser.parse_transaction_input( tx_response['input']) print("transaction input parse:", tx_hash) print(input_result) # 解析该交易在receipt里输出的output,即交易调用的方法的return值 output_result = data_parser.parse_receipt_output( input_result['name'], receipt['output']) print("receipt output :", output_result) # 调用一下call,获取数据 print( "\n>>Call:------------------------------------------------------------------------" ) res = client.call(to_address, contract_abi, "get") print("call get result:", res) # 关闭连接 client.finish() except: pass
def get_transaction_info(request): transaction_id = int(request.POST.get('transaction_id')) contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "get_transaction_info", [transaction_id]) client.finish() transaction_info = { "user_id_sell": res[1], "user_id_buy": res[2], "desc": res[3], "commodity_id": res[4], "price": res[5], "state": res[6], "id": transaction_id, } ret_code = 0 if transaction_info["state"] != -999 else -1 response = { "code": ret_code, } if ret_code == 0: response["transaction"] = transaction_info return JsonResponse(response)
def get_arbitration_reason(request): transaction_id = int(request.POST.get('transaction_id')) contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "get_arbitration_reason", [transaction_id]) client.finish() arbitration_reason = res[0] if arbitration_reason == "NULL": ret_code = -1 # no such transaction arbitration_reason = "" else: ret_code = 0 # success return JsonResponse({ "code": ret_code, "arbitration_reason": arbitration_reason, })
def auth_user(request): user_id = request.POST.get('user_id') user_password = request.POST.get('user_password') contract_name = "Admin" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "valid_psd", [user_id, user_password]) client.finish() code_map = { 1: 0, # success -1: -1, # user don't exists -2: -2, # wrong password } ret_code = code_map[res[0]] return JsonResponse({"code": ret_code})
def get_user_info(request): user_id = request.POST.get('user_id') contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "get_user_info", [user_id]) client.finish() user_info = { "id": res[0], "info": res[1], "balance": res[2], "state": res[3], } ret_code = 0 if user_info["state"] != -999 else -1 response = { "code": ret_code, } if ret_code == 0: response["user"] = user_info return JsonResponse(response)
class HelloWorld: # name of abi address = None contract_abi_string = '''[{"constant": false, "inputs": [{"name": "n", "type": "string"}], "name": "set", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "get", "outputs": [{"name": "", "type": "string"}], "payable": false, "stateMutability": "view", "type": "function"}, {"inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "newname", "type": "string"}], "name": "onset", "type": "event", "topic": "0xafb180742c1292ea5d67c4f6d51283ecb11e49f8389f4539bef82135d689e118"}]''' contract_abi = None data_parser = DatatypeParser() client = None def __init__(self, address): self.client = BcosClient() self.address = address self.contract_abi = json.loads(self.contract_abi_string) self.data_parser.set_abi(self.contract_abi) def deploy(self, contract_bin_file): result = self.client.deployFromFile(contract_bin_file) self.address = result["contractAddress"] return result # ------------------------------------------ def set(self, n): func_name = 'set' args = [n] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def get(self): func_name = 'get' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result
def get_commodity_info(request): commodity_id = int(request.POST.get('commodity_id')) contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, "get_commodity_info", [commodity_id]) client.finish() commodity_info = { "owner": res[0], "name": res[1], "image": res[2], "desc": res[3], "price": res[4], "state": res[5], "id": res[6], "type": res[7], } ret_code = 0 if commodity_info["state"] != -999 else -1 response = { "code": ret_code, } if ret_code == 0: response["commodity"] = commodity_info return JsonResponse(response)
def fisco_select_data(self, func_name, args): client = BcosClient() try: print('start') res = client.call(self.contract_address, self.contract_abi, func_name, args) print("call get result:", res) # 关闭连接 client.finish() return res except: return None
def call_contract2(contract_addr: str, contract_name: str, fn_name: str, args: List = None, signer: Signer_Impl = None): client = BcosClient() if signer is not None: client.default_from_account_signer = signer data_parser: DatatypeParser = DatatypeParser() data_parser.load_abi_file(f"Contracts/{contract_name}.abi") contract_abi = data_parser.contract_abi ret = client.call(contract_addr, contract_abi, fn_name, args) app.logger.info( f"call contract {contract_name} at {contract_addr}. {fn_name} ({args}) -> {ret}" ) client.finish() return ret
def test(): # 初始化bcos客户端 try: client = BcosClient() while True: model, epoch = client.call(to_address, contract_abi, "QueryGlobalModel") model = deserialize(model) ser_W, ser_b = model['ser_W'], model['ser_b'] nonlocal test_epoch if epoch > test_epoch: test_acc = global_testing(ser_W, ser_b) print("Epoch: {:03}, test_acc: {:.4f}"\ .format(test_epoch, test_acc)) test_epoch = epoch wait() except Exception as e: client.finish() traceback.print_exc()
class Loan_Contract: def __init__(self, address: str): # 从文件加载abi定义 # Now file has been complied. Use .abi directly. if os.path.isfile(client_config.solc_path) or os.path.isfile( client_config.solcjs_path): Compiler.compile_file("contracts/Loan.sol") abi_file = "contracts/Loan.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) self.contract_abi = data_parser.contract_abi self.client = BcosClient() self.to_address = address def get_bank_info_by_index(self, index: int): bank_inf = self.client.call(self.to_address, self.contract_abi, "banks", [index]) return {"bankName": bank_inf[0]} def get_company_info_by_index(self, index: int): cp_inf = self.client.call(self.to_address, self.contract_abi, "companies", [index]) return { "companyName": cp_inf[0], "companyType": cp_inf[1], "isTrusted": cp_inf[2], "creditAsset": cp_inf[3], "realMoney": cp_inf[4] } def get_receipt_info_by_index(self, index: int): receipt_inf = self.client.call(self.to_address, self.contract_abi, "receipts", [index]) return { "Name_A": receipt_inf[0], "Name_B": receipt_inf[1], "bankParticipation": receipt_inf[2], "isRealMoney": receipt_inf[3], "amount": receipt_inf[4] } def get_bank_inf_by_name(self, bName: str): bank_inf = self.client.call(self.to_address, self.contract_abi, "getBankInfoByName", [bName]) return {"bankName": bank_inf[0]} def get_company_inf_by_name(self, cpName: str): cp_inf = self.client.call(self.to_address, self.contract_abi, "getCompanyInfoByName", [cpName]) return { "companyName": cp_inf[0], "companyType": cp_inf[1], "isTrusted": cp_inf[2], "creditAsset": cp_inf[3], "realMoney": cp_inf[4] } def get_AmountOfCreditAsset_bank_GiveTo_TrustedCompany( self, bName: str, cpName: str): result = self.client.call( self.to_address, self.contract_abi, "getAmountOfCreditAsset_bankGiveToTrustedCompany", [bName, cpName]) return {"amount": result[0]} def get_company_num(self): result = self.client.call(self.to_address, self.contract_abi, "getCompanyNum") return {"companyNum": result[0]} def get_bank_num(self): result = self.client.call(self.to_address, self.contract_abi, "getBankNum") return {"bankNum": result[0]} def get_receipt_num(self): result = self.client.call(self.to_address, self.contract_abi, "getReceiptNum") return {"receiptNum": result[0]} def exit(self): self.client.finish()
outputresult = data_parser.parse_receipt_output( inputresult['name'], receipt['output']) #print("receipt output :",outputresult) print("举报信息已提交到 Fisco, 交易哈希为", txhash, "举报信息序号为", outputresult[0]) count += 1 elif choice == '2': num = input("已有{}条举报信息,请输入查询序号:(0~{})".format(count + 1, count)) try: num = int(num) except: print("非法序号!") continue if num > count or num < 0: print("序号不在范围内!") continue res = client.call(to_address, contract_abi, "viewComplain", [num]) print("举报信息为:", res) print("正在从ipfs拉取多媒体文件...") file_hash = res[6] res = ipfs_api.cat(file_hash) try: bytes_stream = BytesIO(res) img = Image.open(bytes_stream) img.show() except: pass choice2 = input("是否保存文件到本地? y/n") if choice2 == 'y' or choice2 == 'Y': ipfs_api.get(file_hash) print("文件已保存到当前文件夹,文件名为:", file_hash) else:
class ERC20Mintable: # name of abi address = None contract_abi_string = '''[{"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": true, "internalType": "address", "name": "spender", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Approval", "type": "event", "topic": "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterAdded", "type": "event", "topic": "0x6ae172837ea30b801fbfcdd4108aa1d5bf8ff775444fd70256b44e6bf3dfc3f6"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "account", "type": "address"}], "name": "MinterRemoved", "type": "event", "topic": "0xe94479a9f7e1952cc78f2d6baab678adc1b772d936c6583def489e524cb66692"}, {"anonymous": false, "inputs": [{"indexed": true, "internalType": "address", "name": "from", "type": "address"}, {"indexed": true, "internalType": "address", "name": "to", "type": "address"}, {"indexed": false, "internalType": "uint256", "name": "value", "type": "uint256"}], "name": "Transfer", "type": "event", "topic": "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "addMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "owner", "type": "address"}, {"internalType": "address", "name": "spender", "type": "address"}], "name": "allowance", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "approve", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "balanceOf", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "subtractedValue", "type": "uint256"}], "name": "decreaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "spender", "type": "address"}, {"internalType": "uint256", "name": "addedValue", "type": "uint256"}], "name": "increaseAllowance", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "account", "type": "address"}], "name": "isMinter", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "account", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "mint", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [], "name": "renounceMinter", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"internalType": "uint256", "name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transfer", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "address", "name": "sender", "type": "address"}, {"internalType": "address", "name": "recipient", "type": "address"}, {"internalType": "uint256", "name": "amount", "type": "uint256"}], "name": "transferFrom", "outputs": [{"internalType": "bool", "name": "", "type": "bool"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}]''' contract_abi = None data_parser = DatatypeParser() client = None def __init__(self, address): self.client = BcosClient() self.address = address self.contract_abi = json.loads(self.contract_abi_string) self.data_parser.set_abi(self.contract_abi) def deploy(self, contract_bin_file): result = self.client.deployFromFile(contract_bin_file) self.address = result["contractAddress"] return result # ------------------------------------------ def addMinter(self, account): func_name = 'addMinter' args = [to_checksum_address(account)] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def allowance(self, owner, spender): func_name = 'allowance' args = [to_checksum_address(owner), to_checksum_address(spender)] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def approve(self, spender, amount): func_name = 'approve' args = [to_checksum_address(spender), amount] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def balanceOf(self, account): func_name = 'balanceOf' args = [to_checksum_address(account)] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def decreaseAllowance(self, spender, subtractedValue): func_name = 'decreaseAllowance' args = [to_checksum_address(spender), subtractedValue] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def increaseAllowance(self, spender, addedValue): func_name = 'increaseAllowance' args = [to_checksum_address(spender), addedValue] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def isMinter(self, account): func_name = 'isMinter' args = [to_checksum_address(account)] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def mint(self, account, amount): func_name = 'mint' args = [to_checksum_address(account), amount] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def renounceMinter(self): func_name = 'renounceMinter' args = [] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def totalSupply(self): func_name = 'totalSupply' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def transfer(self, recipient, amount): func_name = 'transfer' args = [to_checksum_address(recipient), amount] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def transferFrom(self, sender, recipient, amount): func_name = 'transferFrom' args = [ to_checksum_address(sender), to_checksum_address(recipient), amount ] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt
class Car_Contract: def __init__(self, address: str): abi_file = "contracts/Con.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) self.contract_abi = data_parser.contract_abi self.client = BcosClient() self.to_address = address def balanceOf(self, addr: str): addr = Web3.toChecksumAddress(addr) new_carowner = self.client.call(self.to_address, self.contract_abi, "balanceOf", [addr]) return new_carowner def tokenURI(self, tokenid: int): # amount = Web3.toChecksumAddress(amount) new_user = self.client.call(self.to_address, self.contract_abi, "tokenURI", [tokenid]) return new_user def transferTo(self, addr: str, tokenid: int): addr = Web3.toChecksumAddress(addr) car_message = self.client.sendRawTransactionGetReceipt( self.to_address, self.contract_abi, "transferTo", [addr, tokenid]) return car_message def tokenOfOwnerByIndex(self, addr: str, index: int): addr = Web3.toChecksumAddress(addr) car_list = self.client.call(self.to_address, self.contract_abi, "tokenOfOwnerByIndex", [addr, index]) return car_list def ownerOf(self, tokenid: int): # amount = Web3.toChecksumAddress(amount) is_carowner = self.client.call(self.to_address, self.contract_abi, "ownerOf", [tokenid]) return is_carowner def is_user(self, amount: str): amount = Web3.toChecksumAddress(amount) is_user = self.client.call(self.to_address, self.contract_abi, "isUser", [amount]) return is_user def new_vehicle(self, chainNumber: int, number: str, brand: str, color: str, quality: str, price: int, day: int): new_vehicle = self.client.sendRawTransactionGetReceipt( self.to_address, self.contract_abi, "newVehicle", [chainNumber, number, brand, color, quality, price, day]) return new_vehicle def reback_vehicle(self, chainNumber: int): reback_vehicle = self.client.sendRawTransactionGetReceipt( self.to_address, self.contract_abi, "rebackVehicle", [chainNumber]) return reback_vehicle def sign_vehicle(self, chainNumber: int): sign_vehicle = self.client.sendRawTransactionGetReceipt( self.to_address, self.contract_abi, "signVehicle", [chainNumber]) return sign_vehicle
# 从文件加载abi定义 contractname = "TestStruct" contractFile = "contracts\\" + contractname + ".abi" abi_parser = DatatypeParser() abi_parser.load_abi_file(contractFile) contract_abi = abi_parser.contract_abi print(client.getNodeVersion()) #如合约未部署,用python console.py deploy TestStruct 部署一次 #或者自行定位链上既有的合约地址 #address = "0x901250d3fcb6cf282134b12acdd0f1d67f265566" address = ContractNote.get_last(contractname) print(address) res = client.call(address, contract_abi, "getUser", ["alice"]) print("call:", res) # User结构体参数示例。合约接口里的结构体,对应python的tuple数据类型 # 注:调用合约时的入参一定是个python数组,因为合约接口参数可能有一到多个 args = [("zero", 78)] res = client.sendRawTransactionGetReceipt(address, contract_abi, "addUser", args) #print("addUser",res) print_receipt_logs_and_txoutput(client, res, contractname) res = client.call(address, contract_abi, "getUser", ["zero"]) print("call:", res) #对应第一个参数User[] memory _users,这个参数本身是个数组,所以,_users是参数数组里的’数组‘ [[]] args = [[("zero", 78), ("yark", 55), ("xar", 23)]] res = client.sendRawTransactionGetReceipt(address, contract_abi, "addUsers",
#部署合约 print( "\n>>Deploy:---------------------------------------------------------------------" ) with open(contract_dir + "/bin/HelloFBoost.bin", 'r') as load_f: contract_bin = load_f.read() load_f.close() result = client.deploy(contract_bin) print("deploy", result) print("new address : ", result["contractAddress"]) contract_name = os.path.splitext(os.path.basename(abi_file))[0] memo = "tx:" + result["transactionHash"] #把部署结果存入文件备查 from client.contractnote import ContractNote ContractNote.save_address(contract_name, result["contractAddress"], int(result["blockNumber"], 16), memo) print( "\n>>Deployment complete :---------------------------------------------------------------------" ) # #发送交易,调用一个改写数据的接口 to_address = result['contractAddress'] #use new deploy address #调用一下call,获取数据 print( "\n>>Call:------------------------------------------------------------------------" ) res = client.call(to_address, contract_abi, "get") print("call get result:", res)
i = 0 for log in logresult: if 'eventname' in log: i = i + 1 print("{}): log name: {} , data: {}".format(i,log['eventname'],log['eventdata'])) #获取对应的交易数据,解析出调用方法名和参数 txresponse = client.getTransactionByHash(txhash) inputresult = data_parser.parse_transaction_input(txresponse['input']) print("transaction input parse:",txhash) print(inputresult) #解析该交易在receipt里输出的output,即交易调用的方法的return值 outputresult = data_parser.parse_receipt_output(inputresult['name'], receipt['output']) print("receipt output :",outputresult) #调用一下call,获取数据 print("\n>>Call:------------------------------------------------------------------------") res = client.call(to_address,contract_abi,"getbalance") print("call getbalance result:",res) res = client.call(to_address,contract_abi,"getbalance1",[100]) print("call getbalance1 result:",res) res = client.call(to_address,contract_abi,"getname") print("call getname:",res) res = client.call(to_address,contract_abi,"getall") print("call getall result:",res) print("demo_tx,total req {}".format(client.request_counter)) client.finish()
def search_commodity(request): keywords = request.POST.get("keywords") keywords = [keyword for keyword in keywords.split(' ') if len(keyword) > 0] commodity_type = request.POST.get("commodity_type") reverse = bool(int(request.POST.get("reverse", '0'))) max_item_count = request.POST.get("page_max_items") page_id = request.POST.get("page_id") if max_item_count is None or page_id is None: max_item_count = page_id = None else: max_item_count = int(max_item_count) page_id = int(page_id) if max_item_count < 1 or page_id < 0: max_item_count = page_id = None if commodity_type is None: query_method = "get_onsale_list" query_args = [] else: commodity_type = int(commodity_type) query_method = "get_onsale_type_list" query_args = [commodity_type] contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, query_method, query_args) commodity_id_list, commodity_count = res commodity_list = [] for commodity_id in commodity_id_list: commodity_info = client.call(contract_address, contract_abi, "get_commodity_info", [commodity_id]) commodity_info = { "owner": commodity_info[0], "name": commodity_info[1], "image": commodity_info[2], "desc": commodity_info[3], "price": commodity_info[4], "state": commodity_info[5], "id": commodity_info[6], "type": commodity_info[7], } if commodity_info["state"] != -999: commodity_list.append(commodity_info) client.finish() commodity_match_score_list = [] for commodity_info in commodity_list: score = 0 for keyword in keywords: score += int(keyword.lower() in commodity_info["name"].lower()) score += int(keyword.lower() in commodity_info["desc"].lower()) commodity_match_score_list.append(score) commodity_list = [ item[0] for item in sorted(iter( i for i in zip(commodity_list, commodity_match_score_list) if i[1] > 0), key=lambda x: x[1], reverse=True) ] if reverse: commodity_list.reverse() if max_item_count is None: page_num = 1 if len(commodity_list) > 0 else 0 else: page_num = (len(commodity_list) + max_item_count - 1) // max_item_count commodity_list = commodity_list[page_id * max_item_count:(page_id + 1) * max_item_count] return JsonResponse({ "commodity_list": commodity_list, "page_num": page_num, })
class HelloEvent: # name of abi address = None contract_abi_string = '''[{"constant": false, "inputs": [{"name": "n", "type": "string"}, {"name": "i", "type": "int256"}, {"name": "key", "type": "string"}], "name": "settwo", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"name": "n", "type": "string"}], "name": "set", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "get", "outputs": [{"name": "", "type": "string"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "n", "type": "string"}, {"name": "i", "type": "bool"}], "name": "setbool", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"name": "n", "type": "string"}, {"name": "i", "type": "int256"}], "name": "setnum", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "newname", "type": "string"}], "name": "on_set", "type": "event", "topic": "0xc86dd792cb0df852949fd9d6a7b5a0d8b1cd57ba9066ad4c8da6a1e5c51c9b9a"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "name", "type": "string"}, {"indexed": true, "name": "age", "type": "int256"}], "name": "on_number", "type": "event", "topic": "0x5b6dab5d6200c978aea486370c307cd2e56212d2cd7326b6879fe6a32dd1dc15"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "name", "type": "string"}, {"indexed": true, "name": "age", "type": "int256"}, {"indexed": true, "name": "key", "type": "string"}], "name": "on_two_indexed", "type": "event", "topic": "0x3913a7a6879be541cb82067407c4976bdf08f9243ea1f2da9b552e490484f7d0"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "addr", "type": "address"}], "name": "on_address", "type": "event", "topic": "0x23ec7e97005133e2ecacfedd26b164f27c5b90bc5fe00a552a4c54eeeea8b40c"}]''' contract_abi = None data_parser = DatatypeParser() client = None def __init__(self, address): self.client = BcosClient() self.address = address self.contract_abi = json.loads(self.contract_abi_string) self.data_parser.set_abi(self.contract_abi) def deploy(self, contract_bin_file): result = self.client.deployFromFile(contract_bin_file) self.address = result["contractAddress"] return result # ------------------------------------------ def settwo(self, n, i, key): func_name = 'settwo' args = [n, i, key] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def set(self, n): func_name = 'set' args = [n] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def get(self): func_name = 'get' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def setbool(self, n, i): func_name = 'setbool' args = [n, i] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def setnum(self, n, i): func_name = 'setnum' args = [n, i] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt
def fisco_add_data_demo1(): try: client = BcosClient() print(client.getinfo()) print(client.client_account) abi_file = os.path.join(settings.SITE_ROOT, "contracts", "UserTempInfo.abi") data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi # 发送交易,调用一个改写数据的接口 # print("\n>>sendRawTransaction:----------------------------------------------------") to_address = '0x2b042831e72894e292507629bec3ae4886f6fe06' # use new deploy address args = ['99999', '武汉', '38.9度', 20000] receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "insert", args) print("receipt:", receipt) # # 调用一下call,获取数据 # args = ['99'] # print("\n>>Call:------------------------------------------------------------------------") # res = client.call(to_address, contract_abi, "select", args) # print("call get result:", res) # 解析receipt里的log print( "\n>>parse receipt and transaction:--------------------------------------" ) tx_hash = receipt['transactionHash'] print("transaction hash: ", tx_hash) log_result = data_parser.parse_event_logs(receipt["logs"]) i = 0 for log in log_result: if 'eventname' in log: i = i + 1 print("{}): log name: {} , data: {}".format( i, log['eventname'], log['eventdata'])) # 获取对应的交易数据,解析出调用方法名和参数 tx_response = client.getTransactionByHash(tx_hash) input_result = data_parser.parse_transaction_input( tx_response['input']) print("transaction input parse:", tx_hash) print(input_result) # 解析该交易在receipt里输出的output,即交易调用的方法的return值 output_result = data_parser.parse_receipt_output( input_result['name'], receipt['output']) print("receipt output :", output_result) # 调用一下call,获取数据 args = ['99999'] print( "\n>>Call:------------------------------------------------------------------------" ) res = client.call(to_address, contract_abi, "select", args) print("call get result:", res) print( "\n>>Call:------------------------------------------------------------------------" ) res = client.call(to_address, contract_abi, "selectLatest", args) print("call get result:", res) # 关闭连接 client.finish() except: pass
class ChainManager: def __init__(self): self.client = BcosClient() self.dataparser = DatatypeParser() self.dataparser.load_abi_file("./pythonsdk/contracts/Receipt2.abi") self.RECEIPT_ABI = self.dataparser.contract_abi self.dataparser.load_abi_file("./pythonsdk/contracts/Company.abi") self.COMPANY_ABI = self.dataparser.contract_abi self.COMPANY_ADDRESS = "0x2d1c577e41809453c50e7e5c3f57d06f3cdd90ce" self.RECEIPT_ADDRESS = "0x98bc6df6b170d66fb5de93cf69b1f8746908f6d5" # res = self.client.load_default_account() self.BANK_ADDRESS = "0x3e4bf936a2ede27947a2c161abbdfc39df4619ab" def __del__(self): self.client.finish() def hexstr2int(self, hexstr): bit = (len(hexstr) - 2) * 4 num = int(hexstr, 16) # hex str to int if num > 2 ** (bit - 1) - 1: num = 2 ** bit - num num = 0 - num return num def login(self, username, password): keystore_file = "{}/{}".format(client_config.account_keyfile_path, username + ".keystore") if os.path.exists(keystore_file) is False: return -1 try: with open(keystore_file, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, password) self.client.client_account = Account.from_key(privkey) except Exception as e: return -1 return 0 def register(self, username, password): ac = Account.create(password) kf = Account.encrypt(ac.privateKey, password) keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, username) # file is exist, account is registed if os.access(keyfile, os.F_OK): return -1 try: with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, password) client_account = Account.from_key(privkey) ps = PermissionService("./pythonsdk/contracts/precompile") ps.grant("t_rep1", client_account.address) ps.grant("t_company", client_account.address) del ps # write file failed except Exception as e: return -2 return 0 def sign(self, username, password, info): keystore_file = "{}/{}".format(client_config.account_keyfile_path, username + ".keystore") if os.path.exists(keystore_file) is False: return -1 try: with open(keystore_file, "r") as dump_f: keytext = json.load(dump_f) privkey = Account.decrypt(keytext, password) msg = encode_defunct(text=info) signed_msg = Account.sign_message(msg, privkey) v = signed_msg['v'] r = signed_msg['r'] s = signed_msg['s'] return v, r, s except Exception as e: print(e) return -1 def registerCom(self, username, name, addr, credit, comtype, vrs): ''' authority ''' info = username + name + addr + credit + comtype msg = encode_defunct(text=info) bank_addr = Account.recover_message(msg, vrs=vrs) # 没有授权 if not bank_addr.lower() == self.BANK_ADDRESS: return -4 ''' register company ''' log = self.client.sendRawTransactionGetReceipt(self.COMPANY_ADDRESS, self.COMPANY_ABI, "register", [name,addr,credit,comtype]) output = log['output'] ret = self.hexstr2int(output) return ret def queryCom(self, name): info = self.client.call(self.COMPANY_ADDRESS, self.COMPANY_ABI, "queryCompanyByName", [name]) if info[0] == "此公司不存在": return -1 return info def eraseCom(self, name): log = self.client.sendRawTransactionGetReceipt(self.COMPANY_ADDRESS, self.COMPANY_ABI, "erase", [name]) ret = log['output'] ret = self.hexstr2int(ret) return ret def createReceipt(self, title, fromc, toc, amount, lastTime, comment, vrs=None): bankConfirm = 0 if vrs: info = title+fromc+toc+str(amount)+str(lastTime) msg = encode_defunct(text=info) bank_addr = Account.recover_message(msg, vrs=vrs) if bank_addr.lower() == self.BANK_ADDRESS: bankConfirm = 1 info = self.client.call(self.COMPANY_ADDRESS, self.COMPANY_ABI, "queryCompanyByName", [fromc]) owner = info[1] # 账款必须由欠款方创建 if self.client.client_account.address.lower() != owner.lower(): return -5 log = self.client.sendRawTransactionGetReceipt(self.RECEIPT_ADDRESS, self.RECEIPT_ABI, "insert", [title, fromc, toc, amount, lastTime, bankConfirm, comment]) output = log['output'] ret = self.hexstr2int(output) return ret def queryReceipt(self, title): info = self.client.call(self.RECEIPT_ADDRESS, self.RECEIPT_ABI, "queryReceiptByTitle", [title]) if info[0] == "此账款不存在": return -1 return info def queryReceiptOfCom(self, company, isfrom): receipts = self.client.call(self.RECEIPT_ADDRESS, self.RECEIPT_ABI, "queryReceiptByCompany", [company, isfrom]) receipts = receipts[0] res = [] for receipt in receipts: tmp = str(receipt, encoding='utf8').strip('\x00') res.append(tmp) return res def transferReceipt(self, title, fromc, middle, to, amount, newtitle): ret = self.client.sendRawTransactionGetReceipt(self.RECEIPT_ADDRESS, self.RECEIPT_ABI, "transferReceipt", [title, fromc, middle, to, amount, newtitle]) ret = ret['output'] ret = self.hexstr2int(ret) return ret def deleteReceipt(self, title): ret = self.client.sendRawTransactionGetReceipt(self.RECEIPT_ADDRESS, self.RECEIPT_ABI, "removeReceipt", [title]) ret = ret['output'] ret = self.hexstr2int(ret) return ret
class SimpleInfo: # name of abi address = None contract_abi_string = '''[{"constant": false, "inputs": [{"name": "b", "type": "uint256"}], "name": "add", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "getaddress", "outputs": [{"name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [], "name": "getbalance", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "b", "type": "uint256"}], "name": "setbalance", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [{"name": "plus", "type": "uint256"}], "name": "getbalance1", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [], "name": "getall", "outputs": [{"name": "", "type": "string"}, {"name": "", "type": "uint256"}, {"name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [], "name": "getname", "outputs": [{"name": "", "type": "string"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [{"name": "n", "type": "string"}, {"name": "b", "type": "uint256"}, {"name": "a", "type": "address"}], "name": "set", "outputs": [{"name": "", "type": "int256"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [], "name": "reset", "outputs": [{"name": "", "type": "int256"}], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": true, "inputs": [], "name": "getcounter", "outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [], "name": "setempty", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"payable": false, "stateMutability": "nonpayable", "type": "fallback"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "retcode", "type": "int256"}, {"indexed": false, "name": "name", "type": "string"}, {"indexed": false, "name": "balance", "type": "uint256"}, {"indexed": false, "name": "addr", "type": "address"}, {"indexed": false, "name": "memo", "type": "string"}], "name": "on_set", "type": "event", "topic": "0xf2dd11606b57e733a74ee877736d9c8a3da833d5129301d100669eff223a3829"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "retcode", "type": "int256"}, {"indexed": true, "name": "name", "type": "string"}, {"indexed": false, "name": "balance", "type": "uint256"}, {"indexed": true, "name": "addr", "type": "address"}, {"indexed": false, "name": "memo", "type": "string"}], "name": "on_change", "type": "event", "topic": "0x1c6cf3c083b623fd9a108d037161265f6a736e368fc345d3d8ee6fe3f94cf39f"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "retcode", "type": "int256"}, {"indexed": false, "name": "name", "type": "string"}, {"indexed": false, "name": "balance", "type": "uint256"}, {"indexed": false, "name": "addr", "type": "address"}, {"indexed": false, "name": "memo", "type": "string"}], "name": "on_sender", "type": "event", "topic": "0x37c87e74ec29efa2615574aeb214b87c3bb72c1e1fa9fee2892dce36a7e7f3b2"}, {"anonymous": true, "inputs": [{"indexed": false, "name": "retcode", "type": "int256"}, {"indexed": true, "name": "name", "type": "string"}], "name": "on_reset", "type": "event", "topic": "0x9540f234b204da235110a66168f5feb9940a8551da5172974c67392c147630d0"}, {"anonymous": false, "inputs": [{"indexed": false, "name": "msg", "type": "string"}], "name": "on_set_empty", "type": "event", "topic": "0x447fb56343d9108e0b2708a0aa57837bc8f847356d9119daae2d724f6f0724e1"}]''' contract_abi = None data_parser = DatatypeParser() client = None def __init__(self, address): self.client = BcosClient() self.address = address self.contract_abi = json.loads(self.contract_abi_string) self.data_parser.set_abi(self.contract_abi) def deploy(self, contract_bin_file): result = self.client.deployFromFile(contract_bin_file) self.address = result["contractAddress"] return result # ------------------------------------------ def add(self, b): func_name = 'add' args = [b] receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def getaddress(self): func_name = 'getaddress' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def getbalance(self): func_name = 'getbalance' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def setbalance(self, b): func_name = 'setbalance' args = [b] receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def getbalance1(self, plus): func_name = 'getbalance1' args = [plus] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def getall(self): func_name = 'getall' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def getname(self): func_name = 'getname' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def set(self, n, b, a): func_name = 'set' args = [n, b, to_checksum_address(a)] receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def reset(self): func_name = 'reset' args = [] receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def getcounter(self): func_name = 'getcounter' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def setempty(self): func_name = 'setempty' args = [] receipt = self.client.sendRawTransactionGetReceipt(self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output(func_name, receipt['output']) return outputresult, receipt
class Groth16Mixer: # name of abi address = None contract_abi_string = '''[{"inputs": [{"internalType": "uint256", "name": "mk_depth", "type": "uint256"}, {"internalType": "address", "name": "token", "type": "address"}, {"internalType": "uint256[2]", "name": "Alpha", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Beta2", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta1", "type": "uint256[2]"}, {"internalType": "uint256[2]", "name": "Delta2", "type": "uint256[2]"}, {"internalType": "uint256[]", "name": "ABC_coords", "type": "uint256[]"}], "payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "string", "name": "message", "type": "string"}], "name": "LogDebug", "type": "event", "topic": "0xd44da6836c8376d1693e8b9cacf1c39b9bed3599164ad6d8e60902515f83938e"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "message", "type": "bytes32"}], "name": "LogDebug", "type": "event", "topic": "0x05e46912c9be87d8a6830598db8544b61884d9d22f3921597a9a6e8a340914b3"}, {"anonymous": false, "inputs": [{"indexed": false, "internalType": "bytes32", "name": "root", "type": "bytes32"}, {"indexed": false, "internalType": "bytes32[2]", "name": "nullifiers", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes32[2]", "name": "commitments", "type": "bytes32[2]"}, {"indexed": false, "internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "LogMix", "type": "event", "topic": "0x36ed7c3f2ecfb5a5226c478b034d33144c060afe361be291e948f861dcddc618"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_hsig", "outputs": [{"internalType": "bytes32", "name": "hsig", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256", "name": "index", "type": "uint256"}, {"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_nullifier", "outputs": [{"internalType": "bytes32", "name": "nf", "type": "bytes32"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [{"internalType": "uint256[9]", "name": "primary_inputs", "type": "uint256[9]"}], "name": "assemble_public_values", "outputs": [{"internalType": "uint256", "name": "vpub_in", "type": "uint256"}, {"internalType": "uint256", "name": "vpub_out", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": true, "inputs": [], "name": "get_constants", "outputs": [{"internalType": "uint256", "name": "js_in", "type": "uint256"}, {"internalType": "uint256", "name": "js_out", "type": "uint256"}, {"internalType": "uint256", "name": "num_inputs", "type": "uint256"}], "payable": false, "stateMutability": "pure", "type": "function"}, {"constant": false, "inputs": [{"internalType": "bytes32", "name": "commitment", "type": "bytes32"}], "name": "insert", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {"constant": false, "inputs": [{"internalType": "uint256[2]", "name": "a", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "b", "type": "uint256[4]"}, {"internalType": "uint256[2]", "name": "c", "type": "uint256[2]"}, {"internalType": "uint256[4]", "name": "vk", "type": "uint256[4]"}, {"internalType": "uint256", "name": "sigma", "type": "uint256"}, {"internalType": "uint256[9]", "name": "input", "type": "uint256[9]"}, {"internalType": "bytes[2]", "name": "ciphertexts", "type": "bytes[2]"}], "name": "mix", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function"}, {"constant": true, "inputs": [], "name": "token", "outputs": [{"internalType": "address", "name": "", "type": "address"}], "payable": false, "stateMutability": "view", "type": "function"}, {"constant": true, "inputs": [{"internalType": "address", "name": "from", "type": "address"}, {"internalType": "uint256", "name": "value", "type": "uint256"}, {"internalType": "bytes", "name": "data", "type": "bytes"}], "name": "tokenFallback", "outputs": [], "payable": false, "stateMutability": "pure", "type": "function"}]''' contract_abi = None data_parser = DatatypeParser() client = None def __init__(self, address): self.client = BcosClient() self.address = address self.contract_abi = json.loads(self.contract_abi_string) self.data_parser.set_abi(self.contract_abi) def deploy(self, contract_bin_file): result = self.client.deployFromFile(contract_bin_file) self.address = result["contractAddress"] return result # ------------------------------------------ def assemble_hsig(self, primary_inputs): func_name = 'assemble_hsig' args = [primary_inputs] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def assemble_nullifier(self, index, primary_inputs): func_name = 'assemble_nullifier' args = [index, primary_inputs] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def assemble_public_values(self, primary_inputs): func_name = 'assemble_public_values' args = [primary_inputs] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def get_constants(self): func_name = 'get_constants' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def insert(self, commitment): func_name = 'insert' args = [commitment] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def mix(self, a, b, c, vk, sigma, input, ciphertexts): func_name = 'mix' args = [a, b, c, vk, sigma, input, ciphertexts] receipt = self.client.sendRawTransactionGetReceipt( self.address, self.contract_abi, func_name, args) outputresult = self.data_parser.parse_receipt_output( func_name, receipt['output']) return outputresult, receipt # ------------------------------------------ def token(self): func_name = 'token' args = [] result = self.client.call(self.address, self.contract_abi, func_name, args) return result # ------------------------------------------ def tokenFallback(self, from1, value, data): func_name = 'tokenFallback' args = [to_checksum_address(from1), value, data] result = self.client.call(self.address, self.contract_abi, func_name, args) return result
def market_commodity_list_order_by_price(request): commodity_type = request.POST.get("commodity_type") reverse = bool(int(request.POST.get("reverse", '0'))) max_item_count = request.POST.get("page_max_items") page_id = request.POST.get("page_id") if max_item_count is None or page_id is None: max_item_count = page_id = None else: max_item_count = int(max_item_count) page_id = int(page_id) if max_item_count < 1 or page_id < 0: max_item_count = page_id = None if commodity_type is None: query_method = "get_onsale_list" query_args = [] else: commodity_type = int(commodity_type) query_method = "get_onsale_type_list" query_args = [commodity_type] contract_name = "User" contract_address = ContractNote.get_last(contract_name) abi_file = f"contracts/{contract_name}.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi client = BcosClient() res = client.call(contract_address, contract_abi, query_method, query_args) commodity_id_list, commodity_count = res commodity_list = [] for commodity_id in commodity_id_list: commodity_info = client.call(contract_address, contract_abi, "get_commodity_info", [commodity_id]) commodity_info = { "owner": commodity_info[0], "name": commodity_info[1], "image": commodity_info[2], "desc": commodity_info[3], "price": commodity_info[4], "state": commodity_info[5], "id": commodity_info[6], "type": commodity_info[7], } if commodity_info["state"] != -999: commodity_list.append(commodity_info) client.finish() commodity_list.sort(key=lambda commodity_info: commodity_info["price"], reverse=reverse) if max_item_count is None: page_num = 1 if len(commodity_list) > 0 else 0 else: page_num = (len(commodity_list) + max_item_count - 1) // max_item_count commodity_list = commodity_list[page_id * max_item_count:(page_id + 1) * max_item_count] return JsonResponse({ "commodity_list": commodity_list, "page_num": page_num, })
contractname = params["contractname"] data_parser = DatatypeParser(default_abi_file(contractname)) contract_abi = data_parser.contract_abi address = params["address"] if address == "last": address = ContractNote.get_last(contractname) if address == None: sys.exit("can not get last address for [{}],break;".format( contractname)) funcname = params["func"] inputabi = data_parser.func_abi_map_by_name[funcname]["inputs"] args = format_args_by_abi(args, inputabi) print("call {} , address: {}, func: {}, args:{}".format( contractname, address, funcname, args)) result = client.call(address, contract_abi, funcname, args) print("call result: ", result) #-------------------------------------------------------------------------------------------- # console cmd entity #-------------------------------------------------------------------------------------------- validcmds.append("sendtx") usagemsg.append('''sendtx [contractname] [address] [func] [args...] 发送交易调用指定合约的接口,交易如成功,结果会写入区块和状态 send transaction,will commit to blockchain if success eg: sendtx SimpleInfo 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC set alice 100 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC if address is "last" ,then load last address from :{} eg: sendtx SimpleInfo last set 'test' 100 '0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC' '''.format(client_config.contract_info_file)) if cmd == "sendtx": paramsname = ["contractname", "address", "func"]
class ContractManager(object): def __init__(self, sol_file, abi_file, bin_file, DEBUG=True): # 实例化client self.client = BcosClient() self.sol_file = sol_file self.abi_file = abi_file self.bin_file = bin_file self.DEBUG = DEBUG self.data_parser = DatatypeParser() if not os.path.isfile(self.abi_file): self.compile() self.data_parser.load_abi_file(self.abi_file) def compile(self): if os.path.isfile(client_config.solc_path) or os.path.isfile( client_config.solcjs_path): try: Compiler.compile_file(self.sol_file, output_path="contracts/") except CompileError: print(CompileError) else: print(client_config.solc_path) print(client_config.solcjs_path) def checkContractExit(self, contract_name): #address = ContractNote.get_contract_addresses(contract_name) address = ContractNote.get_last(contract_name) if address is None: return False, None else: # 暂时返回低一个就可以了 return True, address def getContractInfo(self, contractAddress): contract_abi = self.data_parser.contract_abi return contract_abi, contractAddress def deploy(self): contract_abi = self.data_parser.contract_abi # 部署合约 if self.DEBUG: print( "\n>>Deploy:---------------------------------------------------------------------" ) with open(self.bin_file, 'r') as load_f: contract_bin = load_f.read() load_f.close() contract_info = self.client.deploy(contract_bin) if self.DEBUG: print("deploy", contract_info) print("new address : ", contract_info["contractAddress"]) contract_name = os.path.splitext(os.path.basename(self.abi_file))[0] memo = "tx:" + contract_info["transactionHash"] # 把部署结果存入文件备查 ContractNote.save_address(contract_name, contract_info["contractAddress"], int(contract_info["blockNumber"], 16), memo) ContractNote.save_contract_address(contract_name, contract_info["contractAddress"]) return contract_abi, contract_info # url = "http://47.113.185.200/group1/M00/00/00/rBjqU16nnLiASd4YAMVnXomRO6M785.mp4" # hashvalue = "c3c93aae6dbed266a0dc55a517960273bc0b79c5ca13afe9ca5ab2d3825540f4" # args = [url, hashvalue] def transaction(self, contract_abi, to_address, method, args): # 发送交易,调用一个改写数据的接口 if self.DEBUG: print( "\n>>sendRawTransaction:----------------------------------------------------------" ) print("to_address", to_address) print("contract_abi", contract_abi) receipt = self.client.sendRawTransactionGetReceipt( to_address, contract_abi, method, args) #receipt = self.client.sendRawTransaction(to_address, contract_abi, method, args) #print(receipt) txhash = receipt['transactionHash'] #if self.DEBUG: # 解析receipt里的log # print("\n>>parse receipt and transaction:----------------------------------------------------------") # print("transaction hash: ", txhash) #logresult = self.data_parser.parse_event_logs(receipt["logs"]) #i = 0 #for log in logresult: # if 'eventname' in log: # i = i + 1 # print("{}): log name: {} , data: {}".format(i, log['eventname'], log['eventdata'])) return receipt def call(self, contract_address, contract_abi, method, args=None): # 调用一下call,获取数据 try: response = self.client.call(contract_address, contract_abi, method, args) return True, response except: import traceback traceback.print_exc() return False, "call contract error"
class Evidence_Contract: def __init__(self, address: str): abi_file = "contracts/EvidenceFactory.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) self.contract_abi = data_parser.contract_abi self.client = BcosClient() self.to_address = address def new_evidence_by_evi(self, evi: str): new_evidence = self.client.sendRawTransactionGetReceipt(self.to_address, self.contract_abi, "newEvidence", [evi]) return {"result": new_evidence["logs"]} def get_evidence_by_address(self, address: str): addr = Web3.toChecksumAddress(address) evidence_msg = self.client.call(self.to_address, self.contract_abi, "getEvidence", [addr]) return {"result": evidence_msg} def add_signatures_by_evi_address(self, address: str): addr = Web3.toChecksumAddress(address) signature = self.client.sendRawTransactionGetReceipt(self.to_address, self.contract_abi, "addSignatures", [addr]) return { "result": signature["logs"] } def verifySigner_by_address(self, address: str): try: addr = Web3.toChecksumAddress(address) signature = self.client.call(self.to_address, self.contract_abi, "verify", [addr]) return { "result": signature[0] } except: return { "address": False } def get_signer_by_index(self, index: int): signature = self.client.call(self.to_address, self.contract_abi, "getSigner", [index]) return { "address": signature[0] } def get_signers_size(self): signers_size = self.client.call(self.to_address, self.contract_abi, "getSignersSize", []) return { "size": signers_size[0] } def get_signers(self): signers = self.client.call(self.to_address, self.contract_abi, "getSigners", []) return { "signers": signers[0] } # contract_address = "0xa2a9d06c3478778e2302bac12115c128334915f4" # a = Evidence_Contract(contract_address) # # # a.client.set_account_by_keystorefile("fengfeng.keystore") # # a.client.set_account_by_keystorefile("fengfeng2.keystore") # fengfeng_privkey = "d6f8c8f9106835ccc8f8d0bbc4b5bf32ff5f8941e69f9f50d075684d10dda7be" # fengfeng2_privkey = "619834a32f41fc9dce7809c3063070af3d78fac577a0c12705984eed0b1a3cb" # # a.client.set_account_by_privkey(fengfeng2_privkey) # # print(a.client.keypair.address) # print("new evidence") # # t = a.new_evidence_by_evi("Hello, world") # print(t) # print(a.get_evidence_by_address(t["result"][0]["address"])) # # print(a.add_signatures_by_evi_address(t["result"][0]["address"])) # print(a.get_evidence_by_address(t["result"][0]["address"])) # # print("==================== 切换账户 ====================") # print("==================== 添加多签用户 ====================") # # a.client.set_account_by_keystorefile("fengfeng.keystore") # # print(a.add_signatures_by_evi_address(t["result"][0]["address"])) # print(a.get_evidence_by_address(t["result"][0]["address"]))
receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "varify", [name.encode('utf8'), 8]) if receipt['status'] == '0x0': print("软件{}验证成功,已开放购买".format(name)) else: print("软件{}授权失败".format(name)) elif choice == '3': name = input("请输入您想购买的软件:") receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "getPrice", [name.encode('utf8')]) if receipt['status'] != '0x0': print("软件{}不存在".format(name)) else: res = client.call(to_address, contract_abi, "getPrice", [name.encode('utf8')]) print("软件价格为:", res[0]) elif choice == '4': name = input("请输入您想购买的软件:") receipt = client.sendRawTransactionGetReceipt(to_address, contract_abi, "buySoftware", [name.encode('utf8')]) if receipt['status'] != '0x0': print("软件购买失败") else: res = client.call(to_address, contract_abi, "buySoftware", [name.encode('utf8')]) print("所购软件在ipfs的哈希值为", res[0]) print("正在从ipfs拉取源代码...") file_hash = res[0] res = ipfs_api.get(file_hash)