def init_web3(providers=default): from cpc_fusion import Web3 if providers is default: w3 = Web3(ens=None) else: w3 = Web3(providers, ens=None) return customize_web3(w3)
def generate_go_ethereum_fixture(destination_dir): with contextlib.ExitStack() as stack: datadir = stack.enter_context(tempdir()) keystore_dir = os.path.join(datadir, 'keystore') ensure_path_exists(keystore_dir) keyfile_path = os.path.join(keystore_dir, KEYFILE_FILENAME) with open(keyfile_path, 'w') as keyfile: keyfile.write(KEYFILE_DATA) genesis_file_path = os.path.join(datadir, 'genesis.json') with open(genesis_file_path, 'w') as genesis_file: genesis_file.write(json.dumps(GENESIS_DATA)) geth_ipc_path_dir = stack.enter_context(tempdir()) geth_ipc_path = os.path.join(geth_ipc_path_dir, 'geth.ipc') geth_port = get_open_port() geth_binary = get_geth_binary() with get_geth_process(geth_binary=geth_binary, datadir=datadir, genesis_file_path=genesis_file_path, geth_ipc_path=geth_ipc_path, geth_port=geth_port): wait_for_socket(geth_ipc_path) web3 = Web3(Web3.IPCProvider(geth_ipc_path)) chain_data = setup_chain_state(web3) # close geth by exiting context # must be closed before copying data dir verify_chain_state(web3, chain_data) # verify that chain state is still valid after closing # and re-opening geth with get_geth_process(geth_binary=geth_binary, datadir=datadir, genesis_file_path=genesis_file_path, geth_ipc_path=geth_ipc_path, geth_port=geth_port): wait_for_socket(geth_ipc_path) web3 = Web3(Web3.IPCProvider(geth_ipc_path)) verify_chain_state(web3, chain_data) static_data = { 'raw_txn_account': RAW_TXN_ACCOUNT, 'keyfile_pw': KEYFILE_PW, } config = merge(chain_data, static_data) pprint.pprint(config) write_config_json(config, datadir) shutil.copytree(datadir, destination_dir)
def init(): # install_solc('v0.4.25') global cpc cpc = int(math.pow(10, 18)) global password password = "******" global owner owner = "0xb3801b8743DEA10c30b0c21CAe8b1923d9625F84" global rnode_succeed rnode_succeed = "0x4A030EC3ea9A813FBb0aFb79cB175c09ce56B3bE" global rnode_failed rnode_failed = "0x8FB5ECa33af7757a8d6cE679C3Ad16cCe007fE7f" global cf cf = Web3(Web3.HTTPProvider('http://127.0.0.1:8521')) cf.personal.unlockAccount("0x4A030EC3ea9A813FBb0aFb79cB175c09ce56B3bE", password) cf.personal.unlockAccount("0x8FB5ECa33af7757a8d6cE679C3Ad16cCe007fE7f", password) global abi abi = {'constant': True, 'inputs': [], 'name': 'getRnodeNum', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': False, 'inputs': [{'name': '_period', 'type': 'uint256'}], 'name': 'setPeriod', 'outputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': False, 'inputs': [], 'name': 'quitRnode', 'outputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': True, 'inputs': [{'name': 'addr', 'type': 'address'}], 'name': 'isContract', 'outputs': [{'name': '', 'type': 'bool'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': True, 'inputs': [{'name': '', 'type': 'address'}], 'name': 'Participants', 'outputs': [{'name': 'lockedDeposit', 'type': 'uint256'}, {'name': 'lockedTime', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': False, 'inputs': [{'name': 'threshold', 'type': 'uint256'}], 'name': 'setRnodeThreshold', 'outputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'function'}, {'constant': True, 'inputs': [{'name': 'addr', 'type': 'address'}], 'name': 'isRnode', 'outputs': [{'name': '', 'type': 'bool'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': True, 'inputs': [], 'name': 'rnodeThreshold', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': False, 'inputs': [], 'name': 'joinRnode', 'outputs': [], 'payable': True, 'stateMutability': 'payable', 'type': 'function'}, {'constant': True, 'inputs': [], 'name': 'getRnodes', 'outputs': [{'name': '', 'type': 'address[]'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'constant': True, 'inputs': [], 'name': 'period', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': False, 'stateMutability': 'view', 'type': 'function'}, {'inputs': [], 'payable': False, 'stateMutability': 'nonpayable', 'type': 'constructor'}, {'anonymous': False, 'inputs': [{'indexed': False, 'name': 'who', 'type': 'address'}, {'indexed': False, 'name': 'lockedDeposit', 'type': 'uint256'}, {'indexed': False, 'name': 'lockedTime', 'type': 'uint256'}], 'name': 'NewRnode', 'type': 'event'}, {'anonymous': False, 'inputs': [{'indexed': False, 'name': 'who', 'type': 'address'}], 'name': 'RnodeQuit', 'type': 'event'} global bin bin = "6080604052603c600155692a5a058fc295ed00000060025534801561002357600080fd5b50336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550610e04806100736000396000f3006080604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630b443f42146100b45780630f3a9f65146100df578063113c84981461010c5780631627905514610123578063595aa13d1461017e578063975dd4b2146101dc578063a8f0769714610209578063b7b3e9da14610264578063b892c6da1461028f578063e508bb8514610299578063ef78d4fd14610305575b600080fd5b3480156100c057600080fd5b506100c9610330565b6040518082815260200191505060405180910390f35b3480156100eb57600080fd5b5061010a60048036038101908080359060200190929190505050610340565b005b34801561011857600080fd5b506101216103a5565b005b34801561012f57600080fd5b50610164600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610564565b604051808215151515815260200191505060405180910390f35b34801561018a57600080fd5b506101bf600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610577565b604051808381526020018281526020019250505060405180910390f35b3480156101e857600080fd5b506102076004803603810190808035906020019092919050505061059b565b005b34801561021557600080fd5b5061024a600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610600565b604051808215151515815260200191505060405180910390f35b34801561027057600080fd5b5061027961061d565b6040518082815260200191505060405180910390f35b610297610623565b005b3480156102a557600080fd5b506102ae6108e8565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156102f15780820151818401526020810190506102d6565b505050509050019250505060405180910390f35b34801561031157600080fd5b5061031a6108f9565b6040518082815260200191505060405180910390f35b6000600360010180549050905090565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561039b57600080fd5b8060018190555050565b6103b93360036108ff90919063ffffffff16565b15156103c457600080fd5b42600154600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010154011115151561041957600080fd5b3373ffffffffffffffffffffffffffffffffffffffff166108fc600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001549081150290604051600060405180830381858888f193505050501580156104a1573d6000803e3d6000fd5b506000600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001819055506104fe33600361095890919063ffffffff16565b507f602a2a9c94f70293aa2be9077f0b2dc89d388bc293fdbcd968274f43494c380d33604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a1565b600080823b905060008111915050919050565b60056020528060005260406000206000915090508060000154908060010154905082565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156105f657600080fd5b8060028190555050565b60006106168260036108ff90919063ffffffff16565b9050919050565b60025481565b61062c33610564565b1515156106c7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a8152602001807f706c65617365206e6f742075736520636f6e74726163742063616c6c2074686981526020017f732066756e6374696f6e0000000000000000000000000000000000000000000081525060400191505060405180910390fd5b6106db3360036108ff90919063ffffffff16565b1515156106e757600080fd5b60025434101515156106f857600080fd5b61074d34600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154610bab90919063ffffffff16565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000018190555042600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101819055506107ee336003610bc990919063ffffffff16565b507f586bfaa7a657ad9313326c9269639546950d589bd479b3d6928be469d6dc290333600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010154604051808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001838152602001828152602001935050505060405180910390a1565b60606108f46003610cf5565b905090565b60015481565b60008260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16905092915050565b60008060008460000160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615156109bb5760009250610ba3565b60008560000160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff02191690831515021790555084600101805490509150600090505b81811015610b9e578373ffffffffffffffffffffffffffffffffffffffff168560010182815481101515610a5457fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415610b91578460010160018303815481101515610aaf57fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168560010182815481101515610aeb57fe5b9060005260206000200160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508460010160018303815481101515610b4757fe5b9060005260206000200160006101000a81549073ffffffffffffffffffffffffffffffffffffffff021916905584600101805480919060019003610b8b9190610d87565b50610b9e565b8080600101915050610a24565b600192505b505092915050565b6000808284019050838110151515610bbf57fe5b8091505092915050565b60008260000160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615610c285760009050610cef565b60018360000160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550826001018290806001815401808255809150509060018203906000526020600020016000909192909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050600190505b92915050565b606081600101805480602002602001604051908101604052809291908181526020018280548015610d7b57602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311610d31575b50505050509050919050565b815481835581811115610dae57818360005260206000209182019101610dad9190610db3565b5b505050565b610dd591905b80821115610dd1576000816000905550600101610db9565b5090565b905600a165627a7a72305820a61199baf3a5c3a2b980fae962df409a696d87b726b0836a07c747a7173bc5370029" global contract_address contract_address = "0x37880d44eE800AD4819117c5B498Fb4D4192c5B2"
def call_contract(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) print( timeTrack.functions.getEmployees().call() ) return timeTrack.functions.getEmployees().call()
def test_local_sendRawTransaction2(userid, serAd): web3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501')) with open( r'D:\9102Hackthon\workstation\cpchain-windows-4.0-amd64\datadir\keystore' + '\\' + serAd) as keyfile: encrypted_key = keyfile.read() private_key_for_senders_account = web3.cpc.account.decrypt( encrypted_key, '123456') from_addr = web3.toChecksumAddress('0x' + serAd) #服务器为发送者 to_addr = web3.toChecksumAddress('0x' + userid) #游戏胜利则服务器发送CPC给玩家 tx_dict = dict( type=0, nonce=web3.cpc.getTransactionCount(from_addr), gasPrice=web3.cpc.gasPrice, #获得Gas Price gas=180000, to=to_addr, #发送给用户 value=500000000, #成功则用户CPC加0.000005CPC data=b'w', chainId=42, ) signed_txn = web3.cpc.account.signTransaction( tx_dict, private_key_for_senders_account, ) print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
def w3(open_port, start_websocket_server): # need new event loop as the one used by server is already running event_loop = asyncio.new_event_loop() endpoint_uri = 'ws://127.0.0.1:{}'.format(open_port) event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop)) provider = WebsocketProvider(endpoint_uri, websocket_timeout=0.01) return Web3(provider)
def valid_register(request): username = request.form["username"] password = request.form["password"] rpassword = request.form["rpassword"] email = request.form["email"] gender = request.form["gender"] birthday = request.form["birthday"] if password != rpassword: return '', username, 'Two passwords are not the same!' w3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501')) newU_addr = w3.personal.newAccount('asdfg') sql = """insert into User (UserName, Gender, Birthday, Password, Email, Address) values ('%s','%s','%s','%s','%s','%s');""" data = (username, gender, birthday, password, email, newU_addr) try: expr = sql%data cursor.execute(expr) cursor.execute("SELECT UserNo FROM User WHERE UserName= '******';" % username) row = cursor.fetchall() db.commit() return row[0][0], username, None except: db.rollback() return '', username, 'This username has been used. Please try another.'
def call_contract(greeter,account_addr,keypath,password,url): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) # Display the default greeting from the contract print('Default contract greeting: {}'.format( greeter.functions.greet().call() )) print('Setting the greeting to Nihao...') tx_hash = greeter.functions.setGreeting('Nihao').raw_transact({ 'gas': 300000, 'from':from_addr, 'value': 0, },keypath,password,42) # Wait for transaction to be mined... w3.cpc.waitForTransactionReceipt(tx_hash) # Display the new greeting value print('Updated contract greeting: {}'.format( greeter.functions.greet().call() )) # When issuing a lot of reads, try this more concise reader: reader = ConciseContract(greeter) assert reader.greet() == "Nihao" a = greeter.events.test.createFilter(fromBlock=0,toBlock='latest') eventlist = a.get_all_entries() print(eventlist)
def test_local_sendRawTransaction1(userid, serAd): web3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501')) # 玩家的keyfile with open( r'D:\9102Hackthon\workstation\cpchain-windows-4.0-amd64\datadir\keystore' + '\\' + userid) as keyfile: encrypted_key = keyfile.read() private_key_for_senders_account = web3.cpc.account.decrypt( encrypted_key, '123456') from_addr = web3.toChecksumAddress('0x' + userid) ##玩家为发送者 to_addr = web3.toChecksumAddress('0x' + serAd) ##游戏失败玩家需发送给CPC给服务器 tx_dict = dict( type=0, nonce=web3.cpc.getTransactionCount(from_addr), gasPrice=web3.cpc.gasPrice, #获得Gas Price gas=180000, to=to_addr, #发送给服务器地址58d0791b5c4ddb460a89feda48a2ed935fb757ec value=300000000, #失败则用户CPC减0.000003 data=b'l', chainId=42, ) signed_txn = web3.cpc.account.signTransaction( tx_dict, private_key_for_senders_account, ) print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
def test_local_sendRawTransaction3(userid, serAd): web3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501')) with open( r'D:\9102Hackthon\workstation\cpchain-windows-4.0-amd64\datadir\keystore' + '\\' + userid) as keyfile: encrypted_key = keyfile.read() private_key_for_senders_account = web3.cpc.account.decrypt( encrypted_key, '123456') from_addr = web3.toChecksumAddress('0x' + userid) # to_addr = web3.toChecksumAddress('0x'+serAd) #异常是自己发给自己记录游戏异常 tx_dict = dict( type=0, nonce=web3.cpc.getTransactionCount(from_addr), gasPrice=web3.cpc.gasPrice, gas=90000, to=from_addr, value=0, data=b'', chainId=42, ) signed_txn = web3.cpc.account.signTransaction( tx_dict, private_key_for_senders_account, ) print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
def web3(request): use_filter_middleware = request.param provider = EthereumTesterProvider() w3 = Web3(provider) if use_filter_middleware: w3.middleware_stack.add(local_filter_middleware) return w3
def update_rate(): cf = Web3(Web3.HTTPProvider(chain)) client = MongoClient(host=mongoHost, port=port) uname = cfg['mongo']['uname'] pwd = cfg['mongo']['password'] db = client['cpchain'] db.authenticate(uname, pwd) rnode_collection = client['cpchain']['rnode'] proposer_collection = client['cpchain']['proposer'] block_collection = client['cpchain']['blocks'] txs_collection = client['cpchain']['txs'] num_collection = client['cpchain']['num'] spend_time = 60 * 10 start_timestamp = int(time.time()) - spend_time txs_count = txs_collection.find({ 'timestamp': { '$gte': start_timestamp } }).count() tps = round(txs_count / spend_time, 2) num_collection.update({'type': 'tps'}, {'$set': {'tps': tps}}, upsert=True) # update bps block_count = block_collection.find({ 'timestamp': { '$gte': start_timestamp } }).count() bps = round(block_count / spend_time, 2) num_collection.update({'type': 'bps'}, {'$set': {'bps': bps}}, upsert=True) client.close() log.info('tps: ' + str(tps) + ', bps: ' + str(bps))
def test_isConnected_disconnected(): """ Web3.isConnected() returns False when configured with a provider that's not connected to a node. """ web3 = Web3(DisconnectedProvider()) assert web3.isConnected() is False
def test_auto_provider_none(): # init without provider succeeds, even when no provider available w3 = Web3() # non-node requests succeed w3.toHex(0) == '0x0' type(w3.providers[0]) == AutoProvider
def main(): target = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'ca', 'bank'] cf = Web3(Web3.HTTPProvider(f'http://127.0.0.1:8499')) for i in target: with open(f'datadir/{i}/address', 'r') as f: addr = f.readline() addr = cf.toChecksumAddress(addr) balance = cf.fromWei(cf.cpc.getBalance(addr), 'ether') print(f'{i}({addr}) => {balance}')
def name_to_hash(name): node = EMPTY_SHA3_BYTES if name: labels = name.split(".") for label in reversed(labels): labelhash = label_to_hash(label) assert isinstance(labelhash, bytes) assert isinstance(node, bytes) node = Web3().keccak(node + labelhash) return node
def callAddEmployee(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) tx_hash = timeTrack.functions.addEmployee().raw_transact({ 'gas': 300000, 'from': from_addr, 'value': 0, }, keypath, password, 42) # Wait for transaction to be mined... w3.cpc.waitForTransactionReceipt(tx_hash) return timeTrack.functions.getEmployees().call()
def callPunchOut(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) tx_hash = timeTrack.functions.doPunchOUT().raw_transact({ 'gas': 300000, 'from': from_addr, 'value': 0, }, keypath, password, 42) # Wait for transaction to be mined... w3.cpc.waitForTransactionReceipt(tx_hash) return call_displayMyHistory()
def call_displayMyHistory(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) print( timeTrack.functions.displayMyPunchIns().call() ) print( timeTrack.functions.displayMyPunchOuts().call() ) return {"punchIns": timeTrack.functions.displayMyPunchIns().call(), "punchOuts": timeTrack.functions.displayMyPunchOuts().call()}
def test_case_1(): cf = Web3(Web3.HTTPProvider("http://127.0.0.1:8521")) cf.cpc.defaultAccount = cf.cpc.accounts[0] cf.personal.unlockAccount(cf.cpc.accounts[0], "password") config = compile_file() contract = cf.cpc.contract(abi=config["abi"], bytecode=config["bin"]) print("===========deploy contract================") estimated_gas = contract.constructor().estimateGas() tx_hash = contract.constructor().transact(dict(gas=estimated_gas)) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) address = tx_receipt['contractAddress'] print("contract address: ", address) network_ins = cf.cpc.contract(abi=config["abi"], address=address) print("============read config===================") host = network_ins.functions.host().call() count = network_ins.functions.count().call() timeout = network_ins.functions.timeout().call() gap = network_ins.functions.gap().call() open = network_ins.functions.open().call() print("host: ", host) print("count: ", count) print("timeout: ", timeout) print("gap: ", gap) print("open: ", open) print("============owner set configs=============") tx_hash = network_ins.functions.updateHost("google.com").transact( {"gas": 8888888}) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) print("set host result: ", tx_receipt["status"]) tx_hash = network_ins.functions.updateCount(10).transact({"gas": 8888888}) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) print("set count result: ", tx_receipt["status"]) tx_hash = network_ins.functions.updateTimeout(300).transact( {"gas": 8888888}) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) print("set timeout result: ", tx_receipt["status"]) tx_hash = network_ins.functions.updateGap(10).transact({"gas": 8888888}) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) print("set gap result: ", tx_receipt["status"]) tx_hash = network_ins.functions.updateOpen(False).transact( {"gas": 8888888}) tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) print("set open result: ", tx_receipt["status"]) print("============read config again===============") host = network_ins.functions.host().call() count = network_ins.functions.count().call() timeout = network_ins.functions.timeout().call() gap = network_ins.functions.gap().call() open = network_ins.functions.open().call() print("host: ", host) print("count: ", count) print("timeout: ", timeout) print("gap: ", gap) print("open: ", open)
def callPunchIn(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) tx_hash = timeTrack.functions.doPunchIN().raw_transact({ 'gas': 300000, 'from': from_addr, 'value': 0, }, keypath, password, 42) # Wait for transaction to be mined... w3.cpc.waitForTransactionReceipt(tx_hash) print("call punch in") return timeTrack.functions.displayPunchTime().call()
def set_default_w3(): global w3 global http_provider provider = HTTPProvider(http_provider) w3 = Web3(provider) # cf. https://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority from web3.middleware import geth_poa_middleware # inject the poa compatibility middleware to the innermost layer w3.middleware_stack.inject(geth_poa_middleware, layer=0) w3.eth.defaultAccount = w3.eth.accounts[0]
def test_campaign(contract_abi, contract_address): abi = contract_abi address = contract_address cf = Web3(Web3.HTTPProvider('http://13.250.201.89:8501')) # cf.cpc.defaultAccount = cf.cpc.accounts[0] campaign = cf.cpc.contract(abi=abi, address=address) withdraw_term = campaign.functions.withdrawTermIdx().call() print("withdraw term: ", withdraw_term) terms = campaign.functions.termIdx().call() print("term: ", terms)
def check_block(url, start=0, end=0): cf = Web3(Web3.HTTPProvider(url)) found = 0 for i in range(int(start), int(end) + 1): b = cf.cpc.getBlock(i) if b is None: print("The block #%d does not exist." % i) else: print(b) found += 1 total = int(end) - int(start) + 1 print("Scanned %d blocks, found %d blocks, %d blocks do not exist." % (total, found, total - found))
def deploy_contract(interface): # init() # cf.cpc.defaultAccount = owner cf = Web3(Web3.HTTPProvider("http://127.0.0.1:8521")) contract = cf.cpc.contract(abi=interface['abi'], bytecode=interface['bin']) estimated_gas = contract.constructor().estimateGas() tx_hash = contract.constructor().transact(dict(gas=estimated_gas)) # get tx receipt to get contract address tx_receipt = cf.cpc.waitForTransactionReceipt(tx_hash) address = tx_receipt['contractAddress'] # contract = cf.cpc.contract(address=address, abi=interface['abi']) return address
def test_local_sendRawTransaction(): web3 = Web3(Web3.HTTPProvider('http://3.1.81.79:8501')) # web3.middleware_stack.inject(geth_poa_middleware, layer=0) # change the keypath to your keystore file with open( '/Users/junchengzhu/go/src/chain/examples/cpchain/data/data21/keystore/key21' ) as keyfile: encrypted_key = keyfile.read() # print(web3.cpc.getBalance(web3.cpc.accounts)) print(web3.cpc.accounts) print('balance:', web3.cpc.getBalance(web3.cpc.accounts[0])) print( "================================encrypted_key======================\n" ) print(encrypted_key) private_key_for_senders_account = web3.cpc.account.decrypt( encrypted_key, 'password') print("private_key_for_senders_account:") print(private_key_for_senders_account) print('coinbase:', web3.cpc.coinbase) from_addr = web3.toChecksumAddress( '0xb3801b8743dea10c30b0c21cae8b1923d9625f84') to_addr = web3.toChecksumAddress( '0xc05302acebd0730e3a18a058d7d1cb1204c4a092') print('gasPrice:', web3.cpc.gasPrice) # set chainId to None if you want a transaction that can be replayed across networks tx_dict = dict( type=0, nonce=web3.cpc.getTransactionCount(from_addr), gasPrice=web3.cpc.gasPrice, gas=90000, to=to_addr, value=123, data=b'', chainId=42, ) signed_txn = web3.cpc.account.signTransaction( tx_dict, private_key_for_senders_account, ) print("signed_txn:") print(signed_txn) print("sendRawTransaction:") print(web3.toHex(signed_txn.rawTransaction)) print(web3.cpc.sendRawTransaction(signed_txn.rawTransaction))
def call_display_global(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) print( timeTrack.functions.displayTotalPunchInCount().call() ) print( timeTrack.functions.displayTotalPunchOutCount().call() ) print( timeTrack.functions.displayTotalOvertimeCount().call() ) print( timeTrack.functions.displayCurrentMsgSender().call() ) return timeTrack.functions.displayTotalOvertimeCount().call()
def creat_contract(filepath, url, contact_name, keypath, password, account_addr, gas): # Solidity source code contract_code_file = open(filepath, "r") contract_source_code = contract_code_file.read() print(contract_source_code) compiled_sol = compile_source(contract_source_code) # Compiled source code contract_interface = compiled_sol[f'<stdin>:{contact_name}'] # web3.py instance w3 = Web3(Web3.HTTPProvider(url)) # set pre-funded account as sender w3.cpc.defaultAccount = w3.cpc.accounts[0] # Instantiate and deploy contract Greeter = w3.cpc.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin']) # Submit the transaction that deploys the contract from_addr = w3.toChecksumAddress(account_addr) tx_hash = Greeter.constructor().raw_transact( { # Increase or decrease gas according to contract conditions 'gas': gas, 'from': from_addr, 'value': 0 }, keypath, password, 42) print('*********', w3.cpc.getTransactionReceipt(tx_hash)) # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = w3.cpc.waitForTransactionReceipt(tx_hash) # tx_receipt1 = w3.cpc.waitForTransactionReceipt(tx_hash_raw) print(tx_receipt) # print(tx_receipt1) # Create the contract instance with the newly-deployed address greeter = w3.cpc.contract( address=tx_receipt.contractAddress, abi=contract_interface['abi'], ) return greeter, w3, tx_receipt.contractAddress
def prepare(): cf = Web3(Web3.HTTPProvider("http://127.0.0.1:8521")) print("current account: ", cf.cpc.accounts) print("balance of owner: ", cf.fromWei(cf.cpc.getBalance(cf.cpc.accounts[0]), "ether")) # cf.personal.newAccount("password") print("current account: ", cf.cpc.accounts) cf.cpc.sendTransaction({ "from": "0xb3801b8743DEA10c30b0c21CAe8b1923d9625F84", "to": "0x4dc8319379E36534b60f5E93C4715d39042723d5", "value": cf.toWei(100000, "ether") }) print( "balance of owner: ", cf.fromWei( cf.cpc.getBalance("0x4dc8319379E36534b60f5E93C4715d39042723d5"), "ether"))
def call_displayMe(): w3 = Web3(Web3.HTTPProvider(url)) from_addr = w3.toChecksumAddress(account_addr) print( timeTrack.functions.displayMyOvertimeCount().call() ) print( timeTrack.functions.displayMyPunchDayNum().call() ) print( timeTrack.functions.displayMyPunchStatus().call() ) print( timeTrack.functions.displayMyAddr().call() ) return {"overtimeCount": timeTrack.functions.displayMyOvertimeCount().call(), "punchStatus": timeTrack.functions.displayMyPunchStatus().call()}