def test_sign(): print("sign test") # ac = Account.create("123456") # print("account priv key: ", ac.privateKey) privkey = "52413c714e418cc6fb06afb1bc3f6c54449c89a82a17c9a117a5aa0bad56a9cd" binprivkey = codecs.decode(privkey, "hex") pubkey = private_key_to_public_key(binprivkey) print("binary priv key: ", decode_hex(privkey)) print("binary pub key: ", pubkey) acforverify = Account.from_key(binprivkey) msg = b"this is a test" msghash = keccak(msg) sig = acforverify._key_obj.sign_msg_hash(msghash) print("pulic key :", acforverify.publickey) vresult = sig.verify_msg_hash(msghash, acforverify.publickey) print("verify result ", vresult) (v, r, s) = ecdsa_raw_sign(msghash, decode_hex(privkey)) vres = ecdsa_raw_verify(msghash, (r, s), pubkey) print("ecdsa raw verify: ", vres) recoverres = ecdsa_raw_recover(msghash, (v, r, s)) print("raw recover result", recoverres) print("hex recover result", encode_hex(recoverres))
def publickey_to_address(self, publickey): publickeybytes = func.bytes_to_list(bytes(decode_hex(publickey))) hashres = sm3.sm3_hash( publickeybytes ) # sm3_hash 对应sm3_implement.py里的sm3_hash,返回的是hex形态的结果 hash_raw = decode_hex(hashres) # 转为bytes addr_raw = hash_raw[-20:] # 截取20个字节 addr = to_checksum_address(addr_raw) # 转为格式化的地址 return addr
def call(self, to_address, contract_abi, fn_name, args=None): cmd = "call" if to_address != "": common.check_and_format_address(to_address) if self.client_account is None: self.load_default_account() functiondata = encode_transaction_data(fn_name, contract_abi, None, args) callmap = dict() callmap["data"] = functiondata callmap["from"] = self.client_account.address callmap["to"] = to_address callmap["value"] = 0 # send transaction to the given group params = [client_config.groupid, callmap] # 发送 response = self.common_request(cmd, params) if "output" in response.keys(): outputdata = response["output"] # 取得方法的abi,签名,参数 和返回类型,进行call返回值的解析 fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi, None, args, None, ) # print("fn_selector",fn_selector) # print("fn_arguments",fn_arguments) fn_output_types = get_fn_abi_types_single(fn_abi, "outputs") # print("output types str:", fn_output_types) decoderesult = decode_single(fn_output_types, decode_hex(outputdata)) return decoderesult return response
def uint(val): try: hexed = Web3.toHex(int(val)) return hexadecimal.decode_hex('0x' + hexed[2:].zfill(64)) except TypeError as e: logging.warning('Could not convert uint {0}: {1}'.format(val, e)) raise
def call(self, to_address, contract_abi, fn_name, args=None): cmd = "call" if self.client_account == None: self.load_default_account() functiondata = encode_transaction_data(fn_name, contract_abi, None, args) callmap = dict() callmap["data"] = functiondata callmap["from"] = self.client_account.address callmap["to"] = to_address callmap["value"] = 0 params = [1, callmap] # 发送 response = self.common_request(cmd, params) outputdata = response["output"] #取得方法的abi,签名,参数 和返回类型,进行call返回值的解析 fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi, None, args, None, ) #print("fn_selector",fn_selector) #print("fn_arguments",fn_arguments) fn_output_types = get_fn_abi_types_single(fn_abi, "outputs") #print("output types str:", fn_output_types) decoderesult = decode_single(fn_output_types, decode_hex(outputdata)) return decoderesult
def call(self, to_address, contract_abi, fn_name, args=None): cmd = "call" if to_address != "": common.check_and_format_address(to_address) self.load_default_account() functiondata = encode_transaction_data(fn_name, contract_abi, None, args) callmap = dict() callmap["data"] = functiondata callmap["from"] = self.default_from_account_signer.get_keypair( ).address callmap["to"] = to_address callmap["value"] = 0 # send transaction to the given group params = [client_config.groupid, callmap] # 发送 response = self.common_request(cmd, params) #print("response : ",response) # check status if "status" in response.keys(): status = int(response["status"], 16) error_message = transaction_status_code.TransactionStatusCode.get_error_message( status) if error_message is not None: raise BcosException( "call error, error message: {}".format(error_message)) if "output" in response.keys(): outputdata = response["output"] # 取得方法的abi,签名,参数 和返回类型,进行call返回值的解析 fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi, None, args, None, ) # print("fn_selector",fn_selector) # print("fn_arguments",fn_arguments) #fn_output_types = get_fn_abi_types_single(fn_abi, "outputs") fn_output_types = get_abi_output_types(fn_abi) try: #decoderesult = decode_single(fn_output_types, decode_hex(outputdata)) #print("fn_output_types",fn_output_types) decoderesult = decode_abi(fn_output_types, decode_hex(outputdata)) return decoderesult except BaseException as e: return response return response
def valid_metamask_message(address, message, signature): #address = attrs['address'] #message = attrs['msg'] #signature = attrs['signed_msg'] r = int(signature[0:66], 16) s = int(add_0x_prefix(signature[66:130]), 16) v = int(add_0x_prefix(signature[130:132]), 16) if v not in (27, 28): v += 27 message_hash = defunct_hash_message(text=message) pubkey = ecrecover_to_pub(decode_hex(message_hash.hex()), v, r, s) signer_address = encode_hex(sha3(pubkey)[-20:]) if signer_address != address.lower(): raise ValidationError({'result': 'Incorrect signature'}, code=400) return True
def ecdsa(order, priv_key): hashed_order = keccak_256( address(order['makerAddress']) + uint(order['makerAmount']) + address(order['makerToken']) + address(order['takerAddress']) + uint(order['takerAmount']) + address(order['takerToken']) + uint(order['nonce']) + uint(order['expiration'])) magic = keccak_256(b'\x19Ethereum Signed Message:\n32' + hashed_order.digest()) v, r, s = ecdsa_raw_sign(magic.hexdigest(), hexadecimal.decode_hex(priv_key)) r = utils.int_to_hex(r) s = utils.int_to_hex(s) # Ensuring that the parameters are correct length if len(r) < 66: r = b'0x0' + r[2:] if len(s) < 66: diff = 66 - len(s) s = '0x' + '0' * diff + s[2:] return v, r, s
def generate_contract_address(from_address: str, nonce: int): rlp_encoded = rlp.encode([decode_hex(from_address), nonce]) hashed = keccak(rlp_encoded) return force_bytes_to_address(hashed)
def parse_output(output, fn_name, contract_abi, args): fn_abi, fn_selector, fn_arguments = fn_abi, fn_selector, fn_arguments = get_function_info( fn_name, contract_abi, None, args, None) fn_output_types = get_fn_abi_types_single(fn_abi, "outputs") decoderesult = decode_single(fn_output_types, decode_hex(output)) return decoderesult
print(encode_hex(signedTxResult.rawTransaction)) url = "http://127.0.0.1:8545" rpc = utils.rpc.HTTPProvider(url) if False: param = [1, encode_hex(signedTxResult.rawTransaction)] # 发送 response = rpc.make_channel_rpc_request("sendRawTransaction", param) print(response) if True: # testing call functiondata = encode_transaction_data("select", contract_abi, None, ['abcefggg']) print("functiondata for call:", functiondata) decoderesult = decode_single("(string)", decode_hex(functiondata[10:])) print("testing decode: ", decoderesult) callmap = dict() callmap["data"] = functiondata callmap["from"] = ac2.address callmap["to"] = contractAddress callmap["value"] = 0 print("calldata", callmap) param = [1, callmap] # 发送 response = rpc.make_request("call", param) print(response) outputdata = response["result"]["output"] retabi = "(int256,uint256,address)" print("data:", outputdata)
def process_events(self): """ Processes the events and pins when a new event comes in """ while self.running: payload = { "method": 'eth_getLogs', "params": [{ "address": self.contract['address'], "fromBlock": self.block_number, }], "id": int(time.time()) } hashes = [] log.debug(payload) req = requests.post(self.server, json=payload, headers={'Content-Type': 'application/json'}) log.debug("received logs from server") try: result = req.json() except json.decoder.JSONDecodeError: log.error("Unexpected response from JSON-RPC server") result = None if result: processed_events = self.process_logs(result.get('result')) for event in processed_events: if event['name'] in self.events: hash_hex = event['args'][self.event_param[ event['name']]] ipfs_hex = '1220' + hash_hex[2:] b58_hash = base58.b58encode(decode_hex(ipfs_hex)) hashes.append(b58_hash) if len(hashes) > 0: self.block_number = hex( int(result['result'][-1]['blockNumber'], 16) + 1) log.debug('New start block {}'.format(self.block_number)) log.info("Total IPFS Hashes found: %s", len(hashes)) log.debug("Hashes found: %s", hashes) for h in hashes: self.pin(h) end = len(self.backlog) i = 0 if end > 0: log.debug("Trying to cleanup the backlog") while h in self.backlog.pop(0): i += 1 res = self.pin(h) if res is True: self.backlog.append(h) # Only process the backlog once until the next iteration if i >= end: break time.sleep(15)
b4 = function_abi_to_4byte_selector(func_abi_byname[0]) print("b4:4byes selector", encode_hex(b4)) # 获得方法“签名”,也就是 func(参数列表)的字符串create(string,uint256,address) funcsig = abi_to_signature(func_abi_byname[0]) print("abi_to_signature:", funcsig) # 获得类似['string', 'uint256', 'address']的输入列表 print(get_abi_input_types(func_abi_byname[0])) # 解析inputdata # 获得方法selector,4个字节,8个hex字符 functionhash = inputdata[0:10] # 10是因为带了0x # 携带的数据 params = inputdata[10:] print("functionhash :%s,inputs %s" % (functionhash, params)) # 转为二进制 bindata = decode_hex(params) print("binary params ", bindata) # decode_single要指定一个字符串的格式描述,解析输入参数 abitext = "(string,uint256,address)" result = decode_single(abitext, bindata) print("!!param decode result ", result) # 将('abc', 1000, '0x7029c502b4f824d19bd7921e9cb74ef92392fb1b') 这样的数据encode一次,进行对比 # 大写:('abc', 1000, '0x7029c502b4F824d19Bd7921E9cb74Ef92392FB1b') inputparams = ('abc', 1000, '0x7029c502b4F824d19Bd7921E9cb74Ef92392FB1b') encoderesult = encode_single(abitext, inputparams) print(encode_hex(encoderesult)) func_abi = func_abi_byname[0] # encode_transaction_data 里对address的编码要大写 with open(r"sample\AddrTableWorker.abi", 'r') as load_f:
def gmhash(primitive: Union[bytes, int, bool] = None, hexstr: str = None, text: str = None ) -> bytes: forhash = bytearray(to_bytes(primitive, hexstr, text)) gmhash = sm3_hash(forhash) gmhash_bytes = decode_hex(gmhash) return gmhash_bytes
def run(self): keyStore = keys.make_keystore_json(decode_hex(self.privateKey), str(self.passWord)) self.response.emit(keyStore)