class TransactionCommon(bcosclient.BcosClient): """ define common functions """ def __init__(self, contract_addr, contract_path, contract_name): """ init client to send transactions """ bcosclient.BcosClient.__init__(self) self.contract_addr = contract_addr self.contract_path = contract_path (fname, extname) = os.path.splitext(contract_name) if extname.endswith("wasm"): # deal with wasm , not compile in this version, todo list self.contract_abi_path = contract_path + "/" + fname + ".abi" self.contract_bin_path = contract_path + "/" + contract_name self.sol_path = contract_path + "/" + contract_name else: # deal with sol files ,may be force re compile sol file ,so set the sol filename self.contract_abi_path = contract_path + "/" + contract_name + ".abi" self.contract_bin_path = contract_path + "/" + contract_name + ".bin" self.sol_path = contract_path + "/" + contract_name + ".sol" if os.path.exists(self.sol_path) is False: raise BcosException(("contract {} not exists," " please put {}.sol into {}").format( contract_name, contract_name, contract_path)) print("contract_abi_path {}, contract_bin_path {}".format( self.contract_abi_path, self.contract_bin_path)) self.dataparser = None if os.path.exists(self.contract_bin_path): self.dataparser = DatatypeParser(self.contract_abi_path) def __del__(self): super().finish() def set_contract_addr(self, contractAddress): self.contract_addr = contractAddress def gen_contract_abi(self, needCover=False): """ get contract abi according to contract_abi_path """ if needCover is False and os.path.exists( self.contract_abi_path) is True: return # backup the abi and bin else: force_write = common.backup_file(self.contract_abi_path) if force_write is False: return force_write = common.backup_file(self.contract_bin_path) if force_write is False: return Compiler.compile_file(self.sol_path, self.contract_path) def send_transaction_getReceipt(self, fn_name, fn_args, gasPrice=30000000, isdeploy=False, from_account_signer=None): """ send transactions to CNS contract with the givn function name and args """ try: contract_abi, args = self.format_abi_args(fn_name, fn_args, isdeploy) contract_bin = None if isdeploy is True and os.path.exists( self.contract_bin_path) is True: with open(self.contract_bin_path, "rb") as f: contract_bin = f.read() f.close() # print(contract_bin) if self.contract_bin_path.endswith("wasm"): contract_bin = encode_hex(contract_bin) else: contract_bin = bytes.decode(contract_bin, "utf-8") if contract_bin is not None and len(contract_bin) > 0x40000: raise BcosException( ("contract bin size overflow," " limit: 0x40000(256K), size: {})").format( len(contract_bin), 16)) receipt = super().sendRawTransactionGetReceipt( self.contract_addr, contract_abi, fn_name, args, contract_bin, gasPrice, from_account_signer=from_account_signer) # check status if "status" not in receipt.keys() or \ "output" not in receipt.keys(): raise BcosError(-1, None, ("send transaction failed" "for empty status and output," "transaction receipt:{}").format(receipt)) status = receipt["status"] status_code = int(status, 16) error_message = transaction_status_code.TransactionStatusCode.get_error_message( status_code) if error_message is not None: raise BcosException( "call error, error message: {}".format(error_message)) if receipt["output"] is None: raise TransactionException(receipt, ("send transaction failed," "status: {}, gasUsed: {}").format( status, receipt["gasUsed"])) if fn_name is not None and fn_args is not None and self.dataparser is not None: output = self.dataparser.parse_receipt_output( fn_name, receipt["output"]) else: output = None return (receipt, output) except BcosError as e: self.logger.error( "send transaction failed, fn_name: {}, fn_args:{}, error_info:{}" .format(fn_name, fn_args, e)) raise e except CompileError as e: self.logger.error( ("send transaction failed for compile soldity failed," "contract_path {}, error_info:{}").format(self.sol_path, e)) raise e def format_abi_args(self, fn_name: str, fn_args, needCover=False): """ format args """ if not self.contract_bin_path.endswith(".wasm"): self.gen_contract_abi(needCover) data_parser = DatatypeParser(self.contract_abi_path) contract_abi = data_parser.contract_abi self.dataparser = data_parser args = None if fn_args is None: return (contract_abi, fn_args) if fn_name in data_parser.func_abi_map_by_name.keys() is None: raise BcosException( "invalid function: {}, the right function list:".format( fn_name, ''.join(data_parser.func_abi_map_by_name.keys()))) if fn_name is not None: fn_abi = data_parser.func_abi_map_by_name[fn_name] inputabi = data_parser.get_function_inputs_abi(fn_name) #inputabi = data_parser.get_function_abi(fn_name) args = format_args_by_function_abi(fn_args, inputabi) #print("args after format:",args) # the constructor with params elif fn_args is not None and contract_abi is not None: abidata = get_constructor_abi(contract_abi) if abidata is not None: inputabi = abidata["inputs"] args = format_args_by_function_abi(fn_args, inputabi) return (contract_abi, args) def call_and_decode(self, fn_name, fn_args=None): """ call and get the output """ contract_abi, args = self.format_abi_args(fn_name, fn_args, False) result = super().call(self.contract_addr, contract_abi, fn_name, args) return result
matchpattern = r"\[(.*?)\]" res = re.findall(matchpattern, "address[]") print(res) res = re.findall(matchpattern, "address[3]") print(res) # 数组参数需要加上中括号,比如[1, 2, 3],数组中是字符串或字节类型,加双引号,例如[“alice”, ”bob”],注意数组参数中不要有空格;布尔类型为true或者false。 strarrayparam = "[\"aaa\",\"bbb\",\"ccc\"]" intarrayparam = "[1,2,3]" boolarrayparam = "[true,true,false]" boolstrarrayparam = "[\"True\",\"false\",\"true\"]" addrarrayparam = "[\"0x7029c502b4f824d19bd7921e9cb74ef92392fb1b\"," \ "\"0x9029c502b4f824d19bd7921e9cb74ef92392fb1b\"," \ "\"0xa029c502b4f824d19bd7921e9cb74ef92392fb1b\"]" res = format_array_args_by_abi(addrarrayparam, "address[]") print(res) res = format_array_args_by_abi(intarrayparam, "int256[]") print(res) res = format_array_args_by_abi(strarrayparam, "string[]") print(res) res = format_array_args_by_abi(boolarrayparam, "bool[]") print(res) res = format_array_args_by_abi(boolstrarrayparam, "bool[]") print(res) from client.datatype_parser import DatatypeParser parser = DatatypeParser("contracts/NoteGroup.abi") fn_abi = parser.get_function_inputs_abi("set_addr") fmt_args = format_args_by_function_abi([addrarrayparam, "testing"], fn_abi) print(fmt_args)
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
from eth_utils.crypto import set_crypto_type, CRYPTO_TYPE_GM, CRYPTO_TYPE_ECDSA set_crypto_type("Gm") data = b'\x87-\x8dP\xab\x0f"N\xf9\x111Dp17\xd0Q\t\xeeDNa\x04Da\xee\x8e\xe9]\x96\xa1<' print("hexdata", data.hex()) data = b'7551ab5643a1690f7b128d0d1790ca6b02a2b5a34653d4311673588d0fa42789' keyfile = "bin/account1.json" account = GM_Account() account.load_from_file(keyfile) print(account.getdetail()) signer = SignTx() signer.KeyPair = account # 从abi文件获得abi的文本定义 parser = DatatypeParser() abi_file = "contracts/HelloWorld.abi" parser.load_abi_file(abi_file) inputparam = ['test123789111'] # print(parser.contract_abi) functiondata = encode_transaction_data("set", parser.contract_abi, None, inputparam) result = parser.parse_transaction_input(functiondata) print("parse tx input :", result) print("functiondata ", functiondata) sighash = keccak(b"set(string)") print(sighash) # 填写一个bcos transaction 的 mapping contractAddress = to_checksum_address( "0x565081461f6f0e1c5bf738013f11f1ca8a5b1537")
def get_functions_by_contract(contract_name): """ get functions according to contract_name """ data_parser = DatatypeParser(default_abi_file(contract_name)) return [*data_parser.func_abi_map_by_name.keys()]
from client.bcosclient import (BcosClient, BcosError) from io import BytesIO from PIL import Image import os import ipfshttpclient from eth_utils import to_checksum_address from client.datatype_parser import DatatypeParser client = BcosClient() ipfs_api = ipfshttpclient.connect('/ip4/127.0.0.1/tcp/5001/http') #info = client.init() #print(client.getinfo()) #从文件加载abi定义 abi_file = "contracts/Chaoyang.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi #部署合约 print("\n\n>>> Deploying Contract, please wait...") with open("contracts/Chaoyang.bin", 'r') as load_f: contract_bin = load_f.read() load_f.close() result = client.deploy(contract_bin) #print("deploy",result) print("contract address : ", result["contractAddress"]) contract_name = os.path.splitext(os.path.basename(abi_file))[0] memo = "tx:" + result["transactionHash"] #把部署结果存入文件备查 from client.contractnote import ContractNote
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 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 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"
from client.bcosclient import ( BcosClient, BcosError ) import os from eth_utils import to_checksum_address from client.datatype_parser import DatatypeParser client = BcosClient() info = client.init() print(info) # 从文件加载abi定义 contractFile = r"./sample/SimpleInfo.abi" abi_parser = DatatypeParser() abi_parser.load_abi_file(contractFile) contract_abi = abi_parser.contract_abi # 部署合约 print("\n>>Deploy:---------------------------------------------------------------------") with open(r"sample/SimpleInfo.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 = contractname = os.path.splitext(os.path.basename(contractFile))[0] memo = "tx:" + result["transactionHash"] # 把部署结果存入文件备查 ContractNote.save_address_to_contract_note(
#这个py文件对应的合约是contracts/TestStruct.sol #注意:TestStruct.sol 的编译器版本是solc6以上 from client.contractnote import ContractNote from client.bcosclient import (BcosClient, BcosError) import os from eth_utils import to_checksum_address from client.datatype_parser import DatatypeParser from console_utils.console_common import print_receipt_logs_and_txoutput client = BcosClient() info = client.init() print(info) # 从文件加载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数组,因为合约接口参数可能有一到多个
import rlp from client.bcostransactions import serializable_unsigned_transaction_from_dict from client.datatype_parser import DatatypeParser from eth_abi import encode_abi, decode_abi from utils.contracts import encode_transaction_data, get_function_info #from utils.contracts import encode_abi from eth_utils import (function_signature_to_4byte_selector, event_abi_to_log_topic, encode_hex, decode_hex) parser = DatatypeParser("contracts/TestStruct.abi") print(parser) fn_name = "addUser" abi = parser.get_function_abi(fn_name) args = [("alice", 23)] print(args) #l = encode_abi(['bytes32', 'bytes32'], [b'a', b'b']) #l = encode_abi([('string','uint256')],[args]) #print(encode_hex(l)) data = '0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000005616c696365000000000000000000000000000000000000000000000000000000' #p = decode_abi(['string','uint256'],decode_hex(data)) #print(p) functiondata = encode_transaction_data(fn_name, parser.contract_abi, None, args) print("functiondata", functiondata) inputabi = ['(string,uint256)'] decodedata = decode_abi(inputabi, decode_hex(data)) print("decodedata", decodedata)
# console cmd entity #-------------------------------------------------------------------------------------------- validcmds.append("call") usagemsg.append('''call [contractname] [address] [func] [args...] call合约的一个只读接口,解析返回值 call a constant funciton of contract and get the returns eg: call SimpleInfo 0xF2c07c98a6829aE61F3cB40c69f6b2f035dD63FC getbalance1 11 if address is "last" ,then load last address from :{} eg: call SimpleInfo last getall '''.format(client_config.contract_info_file)) if cmd == "call": paramsname = ["contractname", "address", "func"] params = fill_params(inputparams, paramsname) args = inputparams[len(paramsname):] 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)
class TestEventPushHandler(ChannelPushHandler): parser = DatatypeParser() def on_push(self, packmsg: ChannelPack): print("EventPushHandler", packmsg.detail()) strmsg = packmsg.data.decode("utf-8") response = json.loads(strmsg) print("response filterID:", response['filterID']) #print("response:", json.dumps(response,indent=4)) loglist = parser.parse_event_logs(response["logs"]) print(json.dumps(loglist, indent=4)) # 从文件加载abi定义 abi_file = "contracts/HelloEvent.abi" parser = data_parser = DatatypeParser(abi_file) contract_abi = data_parser.contract_abi contractnode = ContractNote() address = contractnode.get_last("HelloEvent") print("event contract address is ", address) client = None client = BcosClient() info = client.getinfo() print("client info:", info) params_set = ["aaabbb"] params_setnum_5 = ["setnum_ab", 5] params_setnum_10 = ["setnum_ab", 10] params_settwo_1 = ["settwo_aabb", 10, 'key1'] params_settwo_2 = ["settwo_aabb", 10, 'key2']
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
# 轮询的时间间隔,单位秒 QUERY_INTERVAL = 10 # 最大的执行轮次 MAX_EPOCH = 50 * CLIENT_NUM # 设置模型 n_features = 5 n_class = 2 # 从文件加载abi定义 if os.path.isfile(client_config.solc_path) or os.path.isfile( client_config.solcjs_path): Compiler.compile_file("contracts/CommitteePrecompiled.sol") abi_file = "contracts/CommitteePrecompiled.abi" data_parser = DatatypeParser() data_parser.load_abi_file(abi_file) contract_abi = data_parser.contract_abi # 定义合约地址 to_address = "0x0000000000000000000000000000000000005006" # 写一个节点的工作流程 def run_one_node(node_id): """指定一个node id,并启动一个进程""" batch_size = 100 learning_rate = 0.001 trained_epoch = -1 node_index = int(node_id.split('_')[-1])
class ABICodegen: parser = DatatypeParser() abi_file = "" name = "" # four spaces for indent indent = " " template = "" template_file = "client/codegen_template.py" def __init__(self, abi_file): if len(abi_file) > 0: self.load_abi(abi_file) with open(self.template_file, "r") as f: self.template = f.read() f.close() def load_abi(self, abi_file): self.abi_file = abi_file self.parser.load_abi_file(abi_file) fname = os.path.basename(abi_file) (self.name, ext) = os.path.splitext(fname) def make_function(self, func_abi): func_lines = [] func_def = "def {}(self".format(func_abi["name"]) args_def = "" args_value = "" i = 0 for param in func_abi["inputs"]: if i > 0: args_def += ", " args_value += ", " args_def += param["name"] if param['type'] == "address": args_value += "to_checksum_address({})".format(param["name"]) else: args_value += param["name"] i += 1 if len(args_def) > 0: func_def += ", " + args_def func_def += "):" func_lines.append(func_def) func_lines.append("{}func_name = '{}'".format(self.indent, func_abi["name"])) func_lines.append("{}args = [{}]".format(self.indent, args_value)) if func_abi["constant"] is False: func_lines.append(self.indent + ( "receipt = self.client.sendRawTransactionGetReceipt" "(self.address, self.contract_abi, func_name, args)")) func_lines.append(self.indent + ( "outputresult = self.data_parser.parse_receipt_output" "(func_name, receipt['output'])")) func_lines.append(self.indent + "return outputresult, receipt") if func_abi["constant"] is True: func_lines.append(self.indent + ("result = self.client.call(self.address, " "self.contract_abi, func_name, args)")) func_lines.append(self.indent + "return result") return func_lines def gen_all(self): all_func_code_line = [] func_abi_list = filter_by_type("function", self.parser.contract_abi) for func_abi in func_abi_list: func_lines = self.make_function(func_abi) all_func_code_line.append("") all_func_code_line.append( "# ------------------------------------------") all_func_code_line.extend(func_lines) # print(func_lines) template = self.template template = template.replace("TEMPLATE_CLASSNAME", self.name) template = template.replace("TEMPLATE_ABIFILE", self.abi_file) contract_abi = json.dumps(self.parser.contract_abi).replace("\r", "") contract_abi = contract_abi.replace("\n", " ") template = template.replace("TEMPLATE_CONTRACT_ABI", contract_abi) for line in all_func_code_line: if not line: template += "\n" else: template += self.indent + line + "\n" return template
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, })
@date: 2019-06 ''' import rlp from client.bcostransactions import serializable_unsigned_transaction_from_dict from client.datatype_parser import DatatypeParser import json from eth_abi import decode_single from eth_account.account import Account from eth_utils import decode_hex, encode_hex, to_checksum_address from utils.abi import get_fn_abi_types_single from utils.contracts import encode_transaction_data, get_function_info if (True): parser = DatatypeParser() parser.load_abi_file("contracts/HelloWorld.abi") parser.parse_abi() fn_name = "set" contract_abi = parser.contract_abi args = ["1234"] set_tx_data = encode_transaction_data(fn_name, contract_abi, None, args) print("set_tx_data:", set_tx_data) contractAddress = to_checksum_address( "0x882be29b2d5ac85d6c476fa3fd5f0cae4b4585cc") txmap = dict() txmap["randomid"] = 10003 # 测试用 todo:改为随机数 txmap["gasPrice"] = 30000000 txmap["gasLimit"] = 30000000 txmap["blockLimit"] = 501 # 测试用,todo:从链上查一下 txmap["to"] = contractAddress
def main(argv): try: usagemsg = usage(client_config) cmd, inputparams = parse_commands(argv) precompile = Precompile(cmd, inputparams, contracts_dir + "/precompile") # check cmd valid = check_cmd(cmd, validcmds) if valid is False: printusage(usagemsg, precompile) return # try to callback cns precompile precompile.call_cns() # try to callback consensus precompile precompile.call_consensus() # try to callback config precompile precompile.call_sysconfig_precompile() # try to callback permission precompile precompile.call_permission_precompile() # try to callback crud precompile precompile.call_crud_precompile() # try to callback rpc functions rpcConsole = RPCConsole(cmd, inputparams, contracts_dir) rpcConsole.executeRpcCommand() if cmd == 'showaccount': # must be 2 params common.check_param_num(inputparams, 2, True) name = inputparams[0] password = inputparams[1] keyfile = "{}/{}.keystore".format( client_config.account_keyfile_path, name) # the account doesn't exists if os.path.exists(keyfile) is False: raise BcosException("account {} doesn't exists".format(name)) print("show account : {}, keyfile:{} ,password {} ".format( name, keyfile, password)) try: with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) stat = StatTool.begin() privkey = Account.decrypt(keytext, password) stat.done() print("decrypt use time : %.3f s" % (stat.time_used)) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) print("\n**** please remember your password !!! *****") except Exception as e: raise BcosException(("load account info for [{}] failed," " error info: {}!").format(name, e)) if cmd == 'newaccount': common.check_param_num(inputparams, 2, True) name = inputparams[0] max_account_len = 240 if len(name) > max_account_len: common.print_info( "WARNING", "account name should no more than {}".format( max_account_len)) sys.exit(1) password = inputparams[1] print("starting : {} {} ".format(name, password)) ac = Account.create(password) print("new address :\t", ac.address) print("new privkey :\t", encode_hex(ac.key)) print("new pubkey :\t", ac.publickey) stat = StatTool.begin() kf = Account.encrypt(ac.privateKey, password) stat.done() print("encrypt use time : %.3f s" % (stat.time_used)) keyfile = "{}/{}.keystore".format( client_config.account_keyfile_path, name) print("save to file : [{}]".format(keyfile)) forcewrite = False if not os.access(keyfile, os.F_OK): forcewrite = True else: # old file exist,move to backup file first if (len(inputparams) == 3 and inputparams[2] == "save"): forcewrite = True else: forcewrite = common.backup_file(keyfile) if forcewrite: with open(keyfile, "w") as dump_f: json.dump(kf, dump_f) dump_f.close() print(">>-------------------------------------------------------") print( "INFO >> read [{}] again after new account,address & keys in file:" .format(keyfile)) with open(keyfile, "r") as dump_f: keytext = json.load(dump_f) stat = StatTool.begin() privkey = Account.decrypt(keytext, password) stat.done() print("decrypt use time : %.3f s" % (stat.time_used)) ac2 = Account.from_key(privkey) print("address:\t", ac2.address) print("privkey:\t", encode_hex(ac2.key)) print("pubkey :\t", ac2.publickey) print("\naccount store in file: [{}]".format(keyfile)) print("\n**** please remember your password !!! *****") dump_f.close() # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "deploy": '''deploy abi bin file''' # must be at least 2 params common.check_param_num(inputparams, 1) contractname = inputparams[0].strip() gasPrice = 30000000 # need save address whether or not needSaveAddress = False args_len = len(inputparams) if inputparams[-1] == "save": needSaveAddress = True args_len = len(inputparams) - 1 # get the args fn_args = inputparams[1:args_len] print(fn_args) trans_client = transaction_common.TransactionCommon( "", contracts_dir, contractname) result = trans_client.send_transaction_getReceipt( None, fn_args, gasPrice, True)[0] print("deploy result for [{}] is:\n {}".format( contractname, json.dumps(result, indent=4))) name = contractname address = result['contractAddress'] blocknum = int(result["blockNumber"], 16) ContractNote.save_contract_address(name, address) print("on block : {},address: {} ".format(blocknum, address)) if needSaveAddress is True: ContractNote.save_address(name, address, blocknum) print("address save to file: ", client_config.contract_info_file) else: print('''\nNOTE : if want to save new address as last address for (call/sendtx)\nadd 'save' to cmdline and run again''' ) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "call" or cmd == "sendtx": common.check_param_num(inputparams, 3) paramsname = ["contractname", "address", "func"] params = fill_params(inputparams, paramsname) contractname = params["contractname"] address = params["address"] if address == "last": address = ContractNote.get_last(contractname) if address is None: sys.exit("can not get last address for [{}],break;".format( contractname)) tx_client = transaction_common.TransactionCommon( address, contracts_dir, contractname) fn_name = params["func"] fn_args = inputparams[3:] print("INFO >> {} {} , address: {}, func: {}, args:{}".format( cmd, contractname, address, fn_name, fn_args)) if cmd == "call": result = tx_client.call_and_decode(fn_name, fn_args) print("INFO >> {} result: {}".format(cmd, result)) if cmd == "sendtx": receipt = tx_client.send_transaction_getReceipt( fn_name, fn_args)[0] data_parser = DatatypeParser(default_abi_file(contractname)) # 解析receipt里的log 和 相关的tx ,output print_receipt_logs_and_txoutput(tx_client, receipt, "", data_parser) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "list": RPCConsole.print_rpc_usage() print( "--------------------------------------------------------------------" ) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "txinput": contractname = inputparams[0] inputdata = inputparams[1] abi_path = default_abi_file(contractname) if os.path.isfile(abi_path) is False: raise BcosException( "execute {} failed for {} doesn't exist".format( cmd, abi_path)) try: dataParser = DatatypeParser(abi_path) # print(dataParser.func_abi_map_by_selector) result = dataParser.parse_transaction_input(inputdata) print("\nabifile : ", default_abi_file(contractname)) print("parse result: {}".format(result)) except Exception as e: raise BcosException("execute {} failed for reason: {}".format( cmd, e)) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "checkaddr": address = inputparams[0] result = to_checksum_address(address) print("{} -->\n{}".format(address, result)) # -------------------------------------------------------------------------------------------- # console cmd entity # -------------------------------------------------------------------------------------------- if cmd == "usage": printusage(usagemsg, precompile) except TransactionException as e: common.print_error_msg(cmd, e) except PrecompileError as e: common.print_error_msg(cmd, e) except BcosError as e: common.print_error_msg(cmd, e) except CompileError as e: common.print_error_msg(cmd, e) except ArgumentsError as e: common.print_error_msg(cmd, e) except BcosException as e: common.print_error_msg(cmd, e)
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
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