def verify(req): vc_str = req.GET.get('vc') vc = json.loads(vc_str) sig_from_client = vc.get('sig') issuer_did = vc.get('issuer_did') applicant_did = vc.get('applicant_did') type = vc.get('type') color = vc.get('color') brand = vc.get('brand') battery_capacity = vc.get('battery_capacity') msg = {"issuer_did": issuer_did, 'applicant_did': applicant_did, "type": type, "color": color, "brand": brand, "battery_capacity": battery_capacity} msg = json.dumps(msg) # gen msg hash msghash = defunct_hash_message(text=msg) addr = Account.recoverHash(msghash, signature=sig_from_client) vc_id = vc.get('id') issuer_did = Credential.objects.filter(id=vc_id)[0].issuer_did cre_addr = issuer_did.split(":")[2].lower() if w3.toChecksumAddress(cre_addr) != w3.toChecksumAddress(addr): return JsonResponse({"status": False}) from assets.verify_cred import check_cred status = check_cred(vc_id=vc_id, issuer_did=issuer_did) if status: return JsonResponse({"status": True}) else: return JsonResponse({"status": False})
def EtherTxn(self, to_Address, value, nonce, gasPrice, gas): #乙太幣交易 if self.wt.PrivateKey(self.password): privateKey = self.wt.private else: return 'Password error' address = w3.toChecksumAddress(self.wt.Address()) try: to_Address = w3.toChecksumAddress(to_Address) except: return "Address error" value = int(value * 10**18) try: txn = {#gas * price + value really means MAXGas * price. 'from':address, 'to':to_Address, 'value':int(value), 'gas':int(gas), 'gasPrice':int(gasPrice), # = gas*price+value 'nonce':int(nonce), } # 簽名 送tmp回去給手機 signed_txn = w3.eth.account.signTransaction(txn, private_key=privateKey) tmp = signed_txn.rawTransaction print('type of tmp: ', type(tmp)) # 加密存下來 txhasg = w3.toHex(w3.sha3(signed_txn.rawTransaction)) except: return "Value Error" return tmp.hex()
def SendContract(): tx_hash = Greeter.constructor(w3.toChecksumAddress(setAddr_Importer.get()),w3.toChecksumAddress(setAddr_Exporter.get()),w3.toChecksumAddress(setAddr_Bank.get())).transact() # Wait for the transaction to be mined, and get the transaction receipt tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash) Info = ( "Deployed. gasUsed={gasUsed} \n ContractAddress={contractAddress}".format(**tx_receipt) ) # added by me InfoLabel=Label(win,text=Info,font=('微軟正黑體 bold',10),fg='honeydew2',bg='gray20').place(x=300,y=550,anchor=N)
def subscribe_channel(self, channel_id, address): address = w3.toChecksumAddress(address) channel = str(channel_id) + str(address) self.subscription_flag[channel] = True print("subscribe ", channel) threading.Thread(target=self.subscribe_data, args={channel}).start() return 200
def calc_eth_address(pub_key) -> str: SUBJECT_ASN = ''' Key DEFINITIONS ::= BEGIN SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier, subjectPublicKey BIT STRING } AlgorithmIdentifier ::= SEQUENCE { algorithm OBJECT IDENTIFIER, parameters ANY DEFINED BY algorithm OPTIONAL } END ''' key = asn1tools.compile_string(SUBJECT_ASN) key_decoded = key.decode('SubjectPublicKeyInfo', pub_key) pub_key_raw = key_decoded['subjectPublicKey'][0] pub_key = pub_key_raw[1:len(pub_key_raw)] # https://www.oreilly.com/library/view/mastering-ethereum/9781491971932/ch04.html hex_address = w3.keccak(bytes(pub_key)).hex() eth_address = '0x{}'.format(hex_address[-40:]) eth_checksum_addr = w3.toChecksumAddress(eth_address) return eth_checksum_addr
def send_eth(wallet): # пополняем кошелек ефиром global out_nonce balance = w3.eth.getBalance(out_wallet) if balance < w3.toWei(ETH_FEE * 21000, 'gwei'): message = "Not enough Ether on hot wallet" logger.info(message) send_message(f'tokensend_bot seid: {message}') return False else: signed_txn = w3.eth.account.signTransaction( dict( nonce=out_nonce, gasPrice=w3.toWei(3, 'gwei'), gas=21000, to=w3.toChecksumAddress(wallet), value=w3.toWei(ETH_FEE * 100000, 'gwei'), data=b'', ), OUT_PRIVKEY, ) txhash = w3.eth.sendRawTransaction(signed_txn.rawTransaction) logger.info(txhash.hex()) out_nonce = out_nonce + 1 return txhash
def sign2(user_name, user_hash): # w3.miner.start(1) print(user_name) print(user_hash) flag = w3.personal.unlockAccount(w3.toChecksumAddress(user_hash), user_name) if flag == True: mapping[user_name] = user_hash w3.miner.setEtherBase(mapping[user_name]) w3.miner.start(1) user_flower = greeter.functions.getMyFlowers().transact( {"from": mapping[user_name]}) user_flower = greeter.functions.getMyFlowers().call( {"from": mapping[user_name]}) print("step2") user_seed = greeter.functions.getMyseeds().transact( {"from": mapping[user_name]}) user_seed = greeter.functions.getMyseeds().call( {"from": mapping[user_name]}) print("step3") user_balance = greeter.functions.getBalance().transact( {"from": mapping[user_name]}) user_balance = greeter.functions.getBalance().call( {"from": mapping[user_name]}) print("step4") w3.miner.stop() return render_template("main_view.html", user_name=user_name, user_flower=user_flower, user_seed=user_seed, user_balance=user_balance) else: return render_template("new_account.html") w3.miner.stop()
def send_erc20(amount: float, destination: str, contract_address: str): """Send an ERC20 to an address""" abi_path = os.path.join( os.path.dirname(__file__), "..", "node_modules/boltz-core-grs/build/contracts/IERC20.json", ) abi = open(abi_path, "r") contract = w3.eth.contract(address=contract_address, abi=json.load(abi)["abi"]) tokens = int(amount * pow(10, 18)) transaction_data = contract.functions.transfer( w3.toChecksumAddress(destination), tokens, ).buildTransaction({ 'chainId': w3.eth.chainId, 'nonce': w3.eth.getTransactionCount( "0xA7430D5ef25467365112C21A0e803cc72905cC50"), }) transaction = w3.eth.account.signTransaction( transaction_data, "c62d626999898ce6b5e4cb7122d7f9ffa3c08dda6d1b2b35ec3a4e0b9ebfd5dc", ) return w3.eth.sendRawTransaction(transaction.rawTransaction)
def send_ether(amount: float, destination: str): """Send Ether to an address""" return w3.eth.sendTransaction({ "from": w3.eth.accounts[0], "value": w3.toWei(amount, "ether"), "to": w3.toChecksumAddress(destination) })
def start_exit(self, exitor, uid, prev_tx_blk_num, tx_blk_num): # TODO: Getting the whole block doesn't meet the design concept of plasma cash. # Transactions and its proofs should be passed from previous owner and child chain # before. When exiting, client should have enough information and only query from its # databse. For now, it's just for convenience. When the exchange mechanism between # clients are built, this part should be modified. # issue: https://github.com/omisego/plasma-cash/issues/43 prev_block = self.get_block(prev_tx_blk_num) block = self.get_block(tx_blk_num) prev_tx = prev_block.get_tx_by_uid(uid) prev_block.merklize_transaction_set() prev_tx_proof = prev_block.merkle.create_merkle_proof(uid) tx = block.get_tx_by_uid(uid) block.merklize_transaction_set() tx_proof = block.merkle.create_merkle_proof(uid) self.root_chain.functions.startExit(rlp.encode(prev_tx), prev_tx_proof, prev_tx_blk_num, rlp.encode(tx), tx_proof, tx_blk_num).transact({ 'from': w3.toChecksumAddress(exitor) })
def get_contract(self, path): file_name = path.split('/')[1] abi = json.load( open('contract_data/%s.json' % (file_name.split('.')[0]))) contract = w3.eth.contract(address=w3.toChecksumAddress(contractAddr), abi=abi) return contract
def sign_tx( *, nonce: int, gas_price: int, gas: int, private_key: str, chain_id: int, data: Optional[str] = None, value: Optional[int] = None, to: Optional[str] = None, ) -> SignedTx: tx: Dict[str, Any] = { "gas": gas, "gasPrice": gas_price, "nonce": nonce, "chainId": chain_id } if to: tx["to"] = w3.toChecksumAddress(to) if value: tx["value"] = value if data: tx["data"] = data signed = w3.eth.account.signTransaction(tx, private_key) return SignedTx(tx_hash=signed.hash.hex(), raw_tx=signed.rawTransaction.hex())
def get_contract(self, path): file_name = path.split('/')[1] abi = json.load( open('contract_data/%s.json' % (file_name.split('.')[0]))) contract = w3.eth.contract(address=w3.toChecksumAddress( plasma_config['ROOT_CHAIN_CONTRACT_ADDRESS']), abi=abi) return contract
def unsubscribe_channel(self, channel_id, address): address = w3.toChecksumAddress(address) channel = str(channel_id) + str(address) print("unsubscribe ", channel) self.redis_pub_sub.pubsub_numsub(channel) self.subscription_flag[channel] = False return 200
def amountStamps(sender_id): w3 = Web3( HTTPProvider( 'https://rinkeby.infura.io/cc1357bd5e1347d3b9a3433085e61ae5')) # check the Addresses and the Amount of the Sender if w3.isAddress(sender_id) == False or w3.isAddress(Stamp_id) == False: return None # load the contract for the Stamp address_contract = w3.toChecksumAddress(Stamp_id) contract = w3.eth.contract(address=address_contract, abi=EIP20_ABI) # load the amount of Stamps for the sender address_sender = w3.toChecksumAddress(sender_id) stamp_amount = contract.call().balanceOf(address_sender) return (stamp_amount)
def deposit(self, amount, depositor, currency): value = w3.toWei(amount, 'ether') if currency == '0x' + '00' * 20 else 0 self.root_chain.functions.deposit(currency, amount).transact({ 'from': w3.toChecksumAddress(depositor), 'value': value })
def decode_transaction_raw(transaction_raw: str) -> dict: """ Decode XinFin transaction raw. :param transaction_raw: XinFin transaction raw. :type transaction_raw: str :returns: dict -- XinFin decoded transaction. >>> from pyxdc.utils import decode_transaction_raw >>> decode_transaction_raw(transaction_raw="0xf90703058504a817c800831e84808080b906b0608060405234801561001057600080fd5b506040518060400160405280600581526020017f48656c6c6f0000000000000000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610166565b82805461006e90610105565b90600052602060002090601f01602090048101928261009057600085556100d7565b82601f106100a957805160ff19168380011785556100d7565b828001600101855582156100d7579182015b828111156100d65782518255916020019190600101906100bb565b5b5090506100e491906100e8565b5090565b5b808211156101015760008160009055506001016100e9565b5090565b6000600282049050600182168061011d57607f821691505b6020821081141561013157610130610137565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b61053b806101756000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063a413686214610046578063cfae321714610062578063ef690cc014610080575b600080fd5b610060600480360381019061005b91906102e3565b61009e565b005b61006a6100b8565b604051610077919061035d565b60405180910390f35b61008861014a565b604051610095919061035d565b60405180910390f35b80600090805190602001906100b49291906101d8565b5050565b6060600080546100c790610433565b80601f01602080910402602001604051908101604052809291908181526020018280546100f390610433565b80156101405780601f1061011557610100808354040283529160200191610140565b820191906000526020600020905b81548152906001019060200180831161012357829003601f168201915b5050505050905090565b6000805461015790610433565b80601f016020809104026020016040519081016040528092919081815260200182805461018390610433565b80156101d05780601f106101a5576101008083540402835291602001916101d0565b820191906000526020600020905b8154815290600101906020018083116101b357829003601f168201915b505050505081565b8280546101e490610433565b90600052602060002090601f016020900481019282610206576000855561024d565b82601f1061021f57805160ff191683800117855561024d565b8280016001018555821561024d579182015b8281111561024c578251825591602001919060010190610231565b5b50905061025a919061025e565b5090565b5b8082111561027757600081600090555060010161025f565b5090565b600061028e610289846103a4565b61037f565b9050828152602081018484840111156102a657600080fd5b6102b18482856103f1565b509392505050565b600082601f8301126102ca57600080fd5b81356102da84826020860161027b565b91505092915050565b6000602082840312156102f557600080fd5b600082013567ffffffffffffffff81111561030f57600080fd5b61031b848285016102b9565b91505092915050565b600061032f826103d5565b61033981856103e0565b9350610349818560208601610400565b610352816104f4565b840191505092915050565b600060208201905081810360008301526103778184610324565b905092915050565b600061038961039a565b90506103958282610465565b919050565b6000604051905090565b600067ffffffffffffffff8211156103bf576103be6104c5565b5b6103c8826104f4565b9050602081019050919050565b600081519050919050565b600082825260208201905092915050565b82818337600083830152505050565b60005b8381101561041e578082015181840152602081019050610403565b8381111561042d576000848401525b50505050565b6000600282049050600182168061044b57607f821691505b6020821081141561045f5761045e610496565b5b50919050565b61046e826104f4565b810181811067ffffffffffffffff8211171561048d5761048c6104c5565b5b80604052505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000601f19601f830116905091905056fea264697066735822122002786b5114bea14354170503b8bffe80a17bb5e4610cb41deca549935965f30864736f6c634300080300331ca0f2704e20656acf4b067c23ff6e7e2bf8e9b6f75383c408607fce7f90ef39aedba07612be142f5202b3970ee9b4c821bd95df4eb007735acc9c145b0d204d697f8c") {'hash': '0x57232e7e3f0e4f5f49cad5074bea10c98ee18efd4371e15c163560b8bc8ebb40', 'from': '0x68bF25F60508C2820d3D72E1806503F0955eFf94', 'to': None, 'nonce': 5, 'gas': 2000000, 'gas_price': 20000000000, 'value': 0, 'data': '0x608060405234801561001057600080fd5b506040518060400160405280600581526020017f48656c6c6f0000000000000000000000000000000000000000000000000000008152506000908051906020019061005c929190610062565b50610166565b82805461006e90610105565b90600052602060002090601f01602090048101928261009057600085556100d7565b82601f106100a957805160ff19168380011785556100d7565b828001600101855582156100d7579182015b828111156100d65782518255916020019190600101906100bb565b5b5090506100e491906100e8565b5090565b5b808211156101015760008160009055506001016100e9565b5090565b6000600282049050600182168061011d57607f821691505b6020821081141561013157610130610137565b5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b61053b806101756000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c8063a413686214610046578063cfae321714610062578063ef690cc014610080575b600080fd5b610060600480360381019061005b91906102e3565b61009e565b005b61006a6100b8565b604051610077919061035d565b60405180910390f35b61008861014a565b604051610095919061035d565b60405180910390f35b80600090805190602001906100b49291906101d8565b5050565b6060600080546100c790610433565b80601f01602080910402602001604051908101604052809291908181526020018280546100f390610433565b80156101405780601f1061011557610100808354040283529160200191610140565b820191906000526020600020905b81548152906001019060200180831161012357829003601f168201915b5050505050905090565b6000805461015790610433565b80601f016020809104026020016040519081016040528092919081815260200182805461018390610433565b80156101d05780601f106101a5576101008083540402835291602001916101d0565b820191906000526020600020905b8154815290600101906020018083116101b357829003601f168201915b505050505081565b8280546101e490610433565b90600052602060002090601f016020900481019282610206576000855561024d565b82601f1061021f57805160ff191683800117855561024d565b8280016001018555821561024d579182015b8281111561024c578251825591602001919060010190610231565b5b50905061025a919061025e565b5090565b5b8082111561027757600081600090555060010161025f565b5090565b600061028e610289846103a4565b61037f565b9050828152602081018484840111156102a657600080fd5b6102b18482856103f1565b509392505050565b600082601f8301126102ca57600080fd5b81356102da84826020860161027b565b91505092915050565b6000602082840312156102f557600080fd5b600082013567ffffffffffffffff81111561030f57600080fd5b61031b848285016102b9565b91505092915050565b600061032f826103d5565b61033981856103e0565b9350610349818560208601610400565b610352816104f4565b840191505092915050565b600060208201905081810360008301526103778184610324565b905092915050565b600061038961039a565b90506103958282610465565b919050565b6000604051905090565b600067ffffffffffffffff8211156103bf576103be6104c5565b5b6103c8826104f4565b9050602081019050919050565b600081519050919050565b600082825260208201905092915050565b82818337600083830152505050565b60005b8381101561041e578082015181840152602081019050610403565b8381111561042d576000848401525b50505050565b6000600282049050600182168061044b57607f821691505b6020821081141561045f5761045e610496565b5b50919050565b61046e826104f4565b810181811067ffffffffffffffff8211171561048d5761048c6104c5565b5b80604052505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6000601f19601f830116905091905056fea264697066735822122002786b5114bea14354170503b8bffe80a17bb5e4610cb41deca549935965f30864736f6c63430008030033', 'chain_id': -4, 'r': '0xf2704e20656acf4b067c23ff6e7e2bf8e9b6f75383c408607fce7f90ef39aedb', 's': '0x7612be142f5202b3970ee9b4c821bd95df4eb007735acc9c145b0d204d697f8c', 'v': 28} """ class Transaction(rlp.Serializable): fields: list = [ ("nonce", big_endian_int), ("gas_price", big_endian_int), ("gas", big_endian_int), ("to", Binary.fixed_length(20, allow_empty=True)), ("value", big_endian_int), ("data", binary), ("v", big_endian_int), ("r", big_endian_int), ("s", big_endian_int), ] def hex_to_bytes(data: str) -> bytes: return to_bytes(hexstr=HexStr(data)) transaction = rlp.decode(hex_to_bytes(transaction_raw), Transaction) decoded_transaction: dict = { "hash": Web3.toHex(keccak(hex_to_bytes(transaction_raw))), "from": w3.eth.account.recover_transaction(transaction_raw), "to": (w3.toChecksumAddress(transaction.to) if transaction.to else None), "nonce": transaction.nonce, "gas": transaction.gas, "gas_price": transaction.gas_price, "value": transaction.value, "data": w3.toHex(transaction.data), "chain_id": ((transaction.v - 35) // 2 if transaction.v % 2 else (transaction.v - 36) // 2), "r": hex(transaction.r), "s": hex(transaction.s), "v": transaction.v } return decoded_transaction
def buttonClick(): if window1.get() == 0: window1.set(1) a = str(ContractAdd.get()) global ContractAddress ContractAddress = w3.toChecksumAddress(a) w1 = secondpage(root, 'Send', 1) bt_Send.wait_window(w1.top) window1.set(0)
def check_balance(private_key): address = b2h(ethereum.utils.privtoaddr(private_key)) print("address: 0x%s" % address) checksum_address = w3.toChecksumAddress(address) balance = w3.fromWei(w3.eth.getBalance(checksum_address), 'ether') return balance
def respond_challenge_exit(self, responder, challenge_tx, uid, tx_blk_num): block = self.get_block(tx_blk_num) respond_tx = block.get_tx_by_uid(uid) block.merklize_transaction_set() tx_proof = block.merkle.create_merkle_proof(uid) self.root_chain.functions.respondChallengeExit( uid, challenge_tx, rlp.encode(respond_tx), tx_proof, tx_blk_num).transact({'from': w3.toChecksumAddress(responder)})
def EtherTxn(to_Address, value, nonce, gasPrice, gas): #乙太幣交易 privateKey = wt.PrivateKey() address = w3.toChecksumAddress(wt.PublicKey()) to_Address = w3.toChecksumAddress(to_Address) txn = {#gas * price + value really means MAXGas * price. 'from':address, 'to':to_Address, 'value':int(value), 'gas':int(gas), 'gasPrice':int(gasPrice), # = gas*price+value 'nonce':int(nonce), } # 簽名 送tmp回去給手機 signed_txn = w3.eth.account.signTransaction(txn, private_key=privateKey) tmp = signed_txn.rawTransaction # 加密存下來 txhasg = w3.toHex(w3.sha3(signed_txn.rawTransaction)) return tmp
def get_list_value(self, address, request_type): """ This will fetch existed list using given details. :param address: Ethereum public address :param request_type: pending_request_type or response_type :return: state_update_data """ address = w3.toChecksumAddress(address) key = str(address) + str(request_type) return self.redis_client.lrange(key, 0, -1)
def decode_raw_tx(raw_tx: str) -> DecodedRawTx: tx: Any = rlp.decode(hex_to_bytes(raw_tx), RPLTransaction) tx_hash = Web3.toHex(keccak(hex_to_bytes(raw_tx))) from_ = w3.eth.account.recover_transaction(raw_tx) to = w3.toChecksumAddress(tx.to) if tx.to else None data = w3.toHex(tx.data) r = hex(tx.r) s = hex(tx.s) chain_id = (tx.v - 35) // 2 if tx.v % 2 else (tx.v - 36) // 2 return DecodedRawTx(**md(tx_hash, from_, to, data, chain_id, r, s, tx.v, tx.gas, tx.gas_price, tx.value, tx.nonce))
def update_list_value(self, address, request_type, index, request_content): """ This will update existed value with new given value in the list. :param address: Ethereum public address :param request_type: pending_request_type or response_type :param index: state index in list :param request_content: state_update_data :return: True or False """ address = w3.toChecksumAddress(address) key = str(address) + str(request_type) return self.redis_client.lset(key, index, request_content)
def _create_keystore(privkey_path: str, pubkey_path: str, password: str = '') -> Tuple[str, str]: private_key, eth_address = get_eth_address() eth_address = auto_w3.toChecksumAddress(eth_address) if password: enc_key = encrypt(password, bytes.fromhex(private_key[2:])).hex() save_to_path(privkey_path, enc_key, 'w+') else: save_to_path(privkey_path, private_key, 'w+') save_to_path(pubkey_path, eth_address, 'w+') return private_key, eth_address
def send(sender_id, sender_key, recipient_id): w3 = Web3( HTTPProvider( 'https://rinkeby.infura.io/cc1357bd5e1347d3b9a3433085e61ae5')) # check the Addresses and the Amount of the Sender if w3.isAddress(sender_id) == False or w3.isAddress( recipient_id) == False or w3.isAddress(Stamp_id) == False: return None if amountStamps(sender_id) < 1: return None # load the contract for the Stamp address_contract = w3.toChecksumAddress(Stamp_id) contract = w3.eth.contract(address=address_contract, abi=EIP20_ABI) # get the nonce for the sender nonce = w3.eth.getTransactionCount(sender_id) # build the Transaction stamp_txn = contract.functions.transfer( w3.toChecksumAddress(recipient_id), 1, ).buildTransaction({ 'chainId': 4, 'gas': 70000, 'gasPrice': w3.toWei('1', 'gwei'), 'nonce': nonce, }) # sign the Transaction signed_txn = w3.eth.account.signTransaction(stamp_txn, private_key=sender_key) #send the Transaction result = w3.eth.sendRawTransaction(signed_txn.rawTransaction) result = w3.toHex(result) return result
def Transaction_out(private_key, toaddr, value, gas, gasprice, nonce): toaddr = w3.toChecksumAddress(toaddr) acct = Account.privateKeyToAccount(private_key) #public_key = acct.address transaction = { 'to': toaddr, 'value': int(Decimal(value) * (10 ** 18)), 'gas': int(gas), 'gasPrice': int(Decimal(gasprice) * (10 ** 18)), 'nonce': nonce, 'chainId': 15 } print(transaction) #key = '0x4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318' try: signed = w3.eth.account.signTransaction(transaction, private_key) print("sendData :" + w3.toHex(signed.rawTransaction)) except Exception as err: print("signTransaction Error : " + str(err)) return (False, nonce, "") try: print("jjjjjjjjjjjjjjnonce : " + str(nonce)) tx_hash = requests.get("https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json() except Exception as err: print("sendRawTransaction Error : " + str(err)) return (False,nonce,str(err)) #判断如果是nonce too low的错误,则将nonce的值自动+1 再请求 if "error" in tx_hash.keys(): try: while tx_hash["error"] == "nonce too low": nonce += 1 transaction = { 'to': toaddr, 'value': int(Decimal(value) * (10 ** 18)), 'gas': int(gas), 'gasPrice': int(Decimal(gasprice) * (10 ** 18)), 'nonce': nonce, 'chainId': 15 } signed = w3.eth.account.signTransaction(transaction, private_key) newtx_hash = requests.get( "https://waltonchain.net:18950/api/sendRawTransaction/" + w3.toHex(signed.rawTransaction)).json() if "error" not in newtx_hash.keys(): return (True, nonce, newtx_hash["tx_hash"]) except Exception as err: print("re Transaction error : " + str(err)) return (False, nonce, str(err)) return (False, nonce, tx_hash["error"]) return (True,nonce,tx_hash["tx_hash"])
def hashOrder(sellTokenAdress, sellTokenAmount, buyTokenAdress, buyTokenAmount, expiry, nonce, contractAdress): hashTypes = [ 'address', 'uint128', 'address', 'uint128', 'uint32', 'uint64', 'address' ] hashData = [ w3.toChecksumAddress(sellTokenAdress), sellTokenAmount, w3.toChecksumAddress(buyTokenAdress), buyTokenAmount, expiry, nonce, w3.toChecksumAddress(contractAdress) ] orderHash = w3.soliditySha3(hashTypes, hashData) return Web3.toHex(orderHash)
def Token_Txn(to_addr, value, nonce): #Token交易 ABI = json.loads( '[{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"tokens","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"buy","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"delContract","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"price","type":"uint256"}],"name":"setPrice","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"tokens","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"tokens","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"tokens","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"tokenOwner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"tokens","type":"uint256"}],"name":"Approval","type":"event"},{"constant":true,"inputs":[{"name":"tokenOwner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowed","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"tokenOwner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balances","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"buyPrice","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"weiToEther","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' ) Token = w3.eth.contract( w3.toChecksumAddress('0xdaFc7DC630DD0974d6d034727cb94Af5A2287b60' ), # deploy the contract /contractaddr abi=ABI) to_addr = w3.toChecksumAddress(to_addr) privateKey = wt.PrivateKey() sender = w3.toChecksumAddress(wt.PublicKey()) txn1 = { 'gas': 70000, 'gasPrice': 1, 'nonce': int(nonce), 'from': sender } txn2 = Token.functions.transfer(to_addr, int(value)).buildTransaction(txn1) signed_txn = w3.eth.account.signTransaction(txn2, private_key=privateKey) tmp = signed_txn.rawTransaction return tmp
def set_file_list(number, file_number, data_type, size, user, period, area, file_addr, file_hash, key, private_key): # number; //设备唯一标识 # file_number; //文件序号 # data_type; //数据类型 # size; //文件大小 # user; //账户 # period; //时段 # area; //地区 # file_addr; //文件索引 # file_hash; //文件校验Hash # key; //AES256位密钥 nonce = init.web3.eth.getTransactionCount(w3.toChecksumAddress(user)) tx = contract_file.functions.set_file_list(number, file_number, data_type, size, w3.toChecksumAddress(user), period, area, file_addr, file_hash, key).buildTransaction({ 'chainId': 10, 'gas': 700000, 'gasPrice': w3.toWei('2', 'gwei'), 'nonce': nonce, }) js = json.dumps(tx, sort_keys=True, indent=4, separators=(',', ':')) print('构造的交易:\n' + str(js)) tx = w3.eth.account.signTransaction(tx, private_key=private_key) js = str(tx).replace(",", ",\n") print('经过签名的交易:\n' + str(js)) ash = init.web3.eth.sendRawTransaction(tx.rawTransaction) print('使用交易hash在区块链上查询到的交易:\n' + str(init.web3.eth.getTransaction(w3.toHex(ash))).replace(",", ",\n")) return