Beispiel #1
0
 def unlock_account(self,
                    account: str,
                    password: str,
                    duration: int = None) -> bool:
     """
     Decrypt the signing material from the key metadata file and cache it on
     the keystore instance is decryption is successful.
     """
     if not self.__signers.get(account):
         try:
             key_metadata = self.__keys[account]
         except KeyError:
             raise self.UnknownAccount(account=account)
         try:
             signing_key = Account.from_key(
                 Account.decrypt(key_metadata, password))
             self.__signers[account] = signing_key
         except TypeError:
             if not password:
                 # It is possible that password is None here passed from the above layer
                 # causing Account.decrypt to crash, expecting a value for password.
                 raise self.AuthenticationFailed(
                     'No password supplied to unlock account.')
             raise
         except ValueError as e:
             raise self.AuthenticationFailed(
                 "Invalid or incorrect ethereum account password.") from e
     return True
Beispiel #2
0
 def get(self, request, format=None):
     safe_funder_public_key = Account.privateKeyToAccount(settings.SAFE_FUNDER_PRIVATE_KEY).address \
         if settings.SAFE_FUNDER_PRIVATE_KEY else None
     safe_sender_public_key = Account.privateKeyToAccount(settings.SAFE_TX_SENDER_PRIVATE_KEY).address \
         if settings.SAFE_TX_SENDER_PRIVATE_KEY else None
     content = {
         'name': 'Safe Relay Service',
         'version': __version__,
         'api_version': self.request.version,
         'https_detected': self.request.is_secure(),
         'settings': {
             'ETHEREUM_NODE_URL':
             settings.ETHEREUM_NODE_URL,
             'ETHEREUM_TRACING_NODE_URL':
             settings.ETHEREUM_TRACING_NODE_URL,
             'ETH_HASH_PREFIX ':
             settings.ETH_HASH_PREFIX,
             'FIXED_GAS_PRICE':
             settings.FIXED_GAS_PRICE,
             'GAS_STATION_NUMBER_BLOCKS':
             settings.GAS_STATION_NUMBER_BLOCKS,
             'NOTIFICATION_SERVICE_PASS':
             bool(settings.NOTIFICATION_SERVICE_PASS),
             'NOTIFICATION_SERVICE_URI':
             settings.NOTIFICATION_SERVICE_URI,
             'SAFE_ACCOUNTS_BALANCE_WARNING':
             settings.SAFE_ACCOUNTS_BALANCE_WARNING,
             'SAFE_CHECK_DEPLOYER_FUNDED_DELAY':
             settings.SAFE_CHECK_DEPLOYER_FUNDED_DELAY,
             'SAFE_CHECK_DEPLOYER_FUNDED_RETRIES':
             settings.SAFE_CHECK_DEPLOYER_FUNDED_RETRIES,
             'SAFE_CONTRACT_ADDRESS':
             settings.SAFE_CONTRACT_ADDRESS,
             'SAFE_DEFAULT_CALLBACK_HANDLER':
             settings.SAFE_DEFAULT_CALLBACK_HANDLER,
             'SAFE_FIXED_CREATION_COST':
             settings.SAFE_FIXED_CREATION_COST,
             'SAFE_FUNDER_MAX_ETH':
             settings.SAFE_FUNDER_MAX_ETH,
             'SAFE_FUNDER_PUBLIC_KEY':
             safe_funder_public_key,
             'SAFE_FUNDING_CONFIRMATIONS':
             settings.SAFE_FUNDING_CONFIRMATIONS,
             'SAFE_PROXY_FACTORY_ADDRESS':
             settings.SAFE_PROXY_FACTORY_ADDRESS,
             'SAFE_PROXY_FACTORY_V1_0_0_ADDRESS':
             settings.SAFE_PROXY_FACTORY_V1_0_0_ADDRESS,
             'SAFE_TX_NOT_MINED_ALERT_MINUTES':
             settings.SAFE_TX_NOT_MINED_ALERT_MINUTES,
             'SAFE_TX_SENDER_PUBLIC_KEY':
             safe_sender_public_key,
             'SAFE_V0_0_1_CONTRACT_ADDRESS':
             settings.SAFE_V0_0_1_CONTRACT_ADDRESS,
             'SAFE_V1_0_0_CONTRACT_ADDRESS':
             settings.SAFE_V1_0_0_CONTRACT_ADDRESS,
             'SAFE_VALID_CONTRACT_ADDRESSES':
             settings.SAFE_VALID_CONTRACT_ADDRESSES,
         }
     }
     return Response(content)
Beispiel #3
0
def sign_create_cancellation(cancellation_params, private_key):
    """
    Function to sign the parameters required to create a cancellation request from the Switcheo Exchange.
    Execution of this function is as follows::

        sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'order_id': '3125550a-04f9-4475-808b-42b5f89d6693',
            'timestamp': 1542088842108,
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': 'dac70ca711bcfbeefbdead2158ef8b15fab1a1....'
        }

    :param cancellation_params: Dictionary with Order ID and timestamp to sign for creating the cancellation.
    :type cancellation_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(cancellation_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = cancellation_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
Beispiel #4
0
 def load_from_keystore(filename, password):
     with open(filename, "r") as f:
         keytext = json.load(f)
         privkey = Account.decrypt(keytext, password)
         ac = Account.from_key(privkey)
         f.close()
         return ac
Beispiel #5
0
 def validate(self):
     name = self.line_name.text()
     password = self.line_pwd.text()
     if name == "bank" and password == "bank":
         bank_window.show()
         bank_window.set_table_content()
     else:
         keyfile = "{}/{}.keystore".format(
             client_config.account_keyfile_path, name)
         # 如果名字不存在
         if os.path.exists(keyfile) is False:
             QMessageBox.warning(self, "error",
                                 "名称 {} 不存在,请先注册。".format(name),
                                 QMessageBox.Yes)
         else:
             print("name : {}, keyfile:{} ,password {}  ".format(
                 name, keyfile, password))
             try:
                 with open(keyfile, "r") as dump_f:
                     keytext = json.load(dump_f)
                     privkey = Account.decrypt(keytext, password)
                     ac2 = Account.from_key(privkey)
                     print("address:\t", ac2.address)
                     print("privkey:\t", encode_hex(ac2.key))
                     print("pubkey :\t", ac2.publickey)
                     company_window.show()
                     company_window.set_basic_info(name)
             except Exception as e:
                 QMessageBox.warning(
                     self, "error", ("Failed to load account info for [{}],"
                                     " error info: {}!").format(name, e),
                     QMessageBox.Yes)
Beispiel #6
0
def sign_create_withdrawal(withdrawal_params, private_key):
    """
    Function to create a withdrawal from the Switcheo Smart Contract.
    Execution of this function is as follows::

        sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'eth',
            'asset_id': 'ETH',
            'amount': '10000000000000000',
            'timestamp': 1542090476102,
            'contract_hash': '0x607af5164d95bd293dbe2b994c7d8aef6bec03bf',
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': '375ddce62e5b3676d5e94ebb9f9a8af5963b....'
        }

    :param withdrawal_params: The parameters to be signed and create a withdraw from Switcheo.
    :type withdrawal_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of the signed transaction to initiate the withdrawal of ETH via the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(withdrawal_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = withdrawal_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
Beispiel #7
0
def sign_create_deposit(deposit_params, private_key):
    """
    Function to sign the deposit parameters required by the Switcheo API.
    Execution of this function is as follows::

        sign_create_deposit(deposit_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'eth',
            'asset_id': 'ETH',
            'amount': '10000000000000000',
            'timestamp': 1542089346249,
            'contract_hash': '0x607af5164d95bd293dbe2b994c7d8aef6bec03bf',
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': 'd4b8491d6514bff28b9f2caa440f51a93f31d....'
        }

    :param deposit_params: Parameters needed to deposit to the Switcheo API and signed in this function.
    :type deposit_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(deposit_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = deposit_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
Beispiel #8
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 show_ecdsa_account(name, password):

            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))
Beispiel #10
0
 def load_default_account(self):
     if (client_config.account_keyfile != None):
         keystorefile = client_config.account_keyfile_path + "/" + client_config.account_keyfile
         with open(keystorefile, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext,
                                       client_config.account_password)
             self.client_account = Account.from_key(privkey)
Beispiel #11
0
 def load_default_account(self):
     try:
         with open(self.keystore_file, "r") as dump_f:
             keytext = json.load(dump_f)
             privkey = Account.decrypt(keytext, client_config.account_password)
             self.client_account = Account.from_key(privkey)
     except Exception as e:
         raise BcosException("load account from {} failed, reason: {}"
                             .format(self.keystore_file, e))
Beispiel #12
0
    def load_default_account(self):
        if client_config.crypto_type == CRYPTO_TYPE_GM:
            # 加载国密账号
            if self.gm_account is not None:
                return  # 不需要重复加载
            try:
                self.gm_account = GM_Account()
                self.gm_account_file = "{}/{}".format(
                    client_config.account_keyfile_path,
                    client_config.gm_account_keyfile)
                if os.path.exists(self.gm_account_file) is False:
                    raise BcosException(
                        ("gm account keyfile file {} doesn't exist, "
                         "please check client_config.py again "
                         "and make sure this account exist").format(
                             self.gm_account_file))
                self.gm_account.load_from_file(
                    self.gm_account_file, client_config.gm_account_password)
                self.keypair = self.gm_account.keypair
                return
            except Exception as e:
                raise BcosException(
                    "load gm account from {} failed, reason: {}".format(
                        self.gm_account_file, e))

        # 默认的 ecdsa 账号
        try:
            if self.ecdsa_account is not None:
                return  # 不需要重复加载
            # check account keyfile
            self.keystore_file = "{}/{}".format(
                client_config.account_keyfile_path,
                client_config.account_keyfile)
            if os.path.exists(self.keystore_file) is False:
                raise BcosException(
                    ("keystore file {} doesn't exist, "
                     "please check client_config.py again "
                     "and make sure this account exist").format(
                         self.keystore_file))
            with open(self.keystore_file, "r") as dump_f:
                keytext = json.load(dump_f)
                privkey = Account.decrypt(keytext,
                                          client_config.account_password)
                self.ecdsa_account = Account.from_key(privkey)
                keypair = BcosKeyPair()
                keypair.private_key = self.ecdsa_account.privateKey
                keypair.public_key = self.ecdsa_account.publickey
                keypair.address = self.ecdsa_account.address
                self.keypair = keypair
        except Exception as e:
            raise BcosException(
                "load account from {} failed, reason: {}".format(
                    self.keystore_file, e))
Beispiel #13
0
def create_account(name, password=""):
    ac = Account.create(password)
    kf = Account.encrypt(ac.privateKey, password)
    keyfile = "{}/{}.keystore".format(client_config.account_keyfile_path, name)

    # if os.access(keyfile, os.F_OK):
    #     common.backup_file(keyfile)

    with open(keyfile, "w") as dump_f:
        json.dump(kf, dump_f)
        dump_f.close()

    return signin_account(name, password)
Beispiel #14
0
 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
Beispiel #15
0
def sign(safe, multi):
    """Sign transation of a Safe.
    This will sign a given transaction hash and return the signature.
    """
    transaction_hash = click.prompt('Please enter transaction hash')
    transaction_hash = codecs.decode(transaction_hash, 'hex_codec')

    choice = click.prompt('What would you like to use for signing?\n(1) Private key\n(2) Account mnemonic\n(3) Safe mnemonic (Yields 2 signatures)\n', type=int)
    
    loops = 1 if not multi else safe.get_threshold()

    account_info = []

    while loops > 0:
        if choice == 1:
            private_key = click.prompt('Please enter private key (Input hidden)', hide_input=True)
            
            address = Account.privateKeyToAccount(private_key).address
            account_info.append((private_key, address))
        elif choice == 2:
            mnemonic = click.prompt('Please enter account mnemonic (Input hidden)', hide_input=True)
            account_info.append(get_account_info_from_mnemonic(mnemonic))
        else:
            mnemonic = click.prompt('Please enter Safe mnemonic (Input hidden)', hide_input=True)
            account_info.append(get_account_info_from_mnemonic(mnemonic, index=0))
            account_info.append(get_account_info_from_mnemonic(mnemonic, index=1))

        for i, info in enumerate(account_info):
            loops -= 1
            private_key = info[0]
            address = info[1]
            v, r, s = ecsign(transaction_hash, codecs.decode(private_key, 'hex_codec'))
            signature = {'v': v, 'r': r, 's': s}
            click.echo('Signature {} ({}):\n\n{}'.format(i, address, json.dumps(signature)))
Beispiel #16
0
    def signTransaction(self, transaction_dict):
        '''
        Sign the hash provided.

        .. WARNING:: *Never* sign a hash that you didn't generate,
            it can be an arbitrary transaction. For example, it might
            send all of your account's ether to an attacker.

        If you would like compatibility with
        :meth:`w3.eth.sign() <web3.eth.Eth.sign>`
        you can use :meth:`~eth_account.messages.defunct_hash_message`.

        Several other message standards are proposed, but none have a clear
        consensus. You'll need to manually comply with any of those message standards manually.

        :param message_hash: the 32-byte message hash to be signed
        :type message_hash: hex str, bytes or int
        :param private_key: the key to sign the message with
        :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
        :returns: Various details about the signature - most
          importantly the fields: v, r, and s
        :rtype: ~eth_account.datastructures.AttributeDict
        '''

        rawtuple = bip32_deserialize(self.__key)

        if rawtuple[0] in PRIVATE:
            # slice the last byte, since it is the WIF-Compressed information
            return Account.signTransaction(transaction_dict, rawtuple[5][:-1])

        if bip32_deserialize(self.__key)[0] not in PRIVATE:
            raise RuntimeError("Cannot sign, only the public key is available")
Beispiel #17
0
def mock_accounts():
    accounts = dict()
    for i in range(NUMBER_OF_MOCK_KEYSTORE_ACCOUNTS):
        account = Account.create()
        filename = KEYFILE_NAME_TEMPLATE.format(month=i+1, address=account.address)
        accounts[filename] = account
    return accounts
Beispiel #18
0
def sign_execute_deposit(deposit_params, private_key, infura_url):
    """
    Function to execute the deposit request by signing the transaction generated from the create deposit function.
    Execution of this function is as follows::

        sign_execute_deposit(deposit_params=create_deposit, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'transaction_hash': '0xcf3ea5d1821544e1686fbcb1f49d423b9ea9f42772ff9ecdaf615616d780fa75'
        }

    :param deposit_params: The parameters generated by the create function that now requires a signature.
    :type deposit_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :param infura_url: The URL used to broadcast the deposit transaction to the Ethereum network.
    :type infura_url: str
    :return: Dictionary of the signed transaction to initiate the deposit of ETH via the Switcheo API.
    """
    create_deposit_upper = deposit_params.copy()
    create_deposit_upper['transaction']['from'] = to_checksum_address(create_deposit_upper['transaction']['from'])
    create_deposit_upper['transaction']['to'] = to_checksum_address(create_deposit_upper['transaction']['to'])
    create_deposit_upper['transaction'].pop('sha256')
    signed_create_txn = Account.signTransaction(create_deposit_upper['transaction'], private_key=private_key)
    execute_signed_txn = binascii.hexlify(signed_create_txn['hash']).decode()

    # Broadcast transaction to Ethereum Network.
    Web3(HTTPProvider(infura_url)).eth.sendRawTransaction(signed_create_txn.rawTransaction)

    return {'transaction_hash': '0x' + execute_signed_txn}
Beispiel #19
0
def main():
    contract = "0xcontractAddress"
    api_key = '1122-122-23443-1133'
    headers = {'accept': 'application/json', 'Content-Type': 'application/json',
               'X-API-KEY': api_key}
    private_key = "0xprivatekeyhexstring"
    api_endpoint = "https://beta.ethvigil.com/api"
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, private_key)
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": api_key,
        "type": "web",
        "contract": contract,
        "web": "https://randomstring.ngrok.io"
    }
    r = requests.post(url=f'{api_endpoint}/hooks/add', json=method_args, headers=headers)
    print(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if not r['success']:
            print('Failed to register webhook with Ethvigil API...')
        else:
            hook_id = r["data"]["id"]
            print('Succeeded in registering webhook with Ethvigil API...')
            print(f'EthVigil Hook ID: {hook_id}')
    else:
        print('Failed to register webhook with Ethvigil API...')
Beispiel #20
0
def get_signature(message: str, key: str) -> dict:
    """ 
    Returns the signature of the given
    message when signed using the reveived
    key as the private key.

    :param message: string
    :param key: string
    :return: dict

        The key param will be interpreted as
        a hex string if possible. In that way,
        if an existing private key is received
        in hex form, the returned signature would
        be the same as if signed from the original
        wallet possesing that key.
        Otherwise a 32 bytes private key will be
        formed by adding leading null-bytes to
        the bytes of the received string.

    """
    try:
        key = bytes.fromhex(key)
    except ValueError:
        key = bytes(key, 'utf-8')
    key = (b'\00' * 32 + key)[-32:]
    acc = Account.from_key(key)

    # the received message is encoded as in EIP-191 "version ``E``"
    encoded = encode_defunct(text=message)

    signed = acc.sign_message(encoded)['signature'].hex()
    return {"address": acc.address, "signature": signed, "message": message}
Beispiel #21
0
 def integrations(self):
     if not self._initialized:
         return None
     url = self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/list'
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address
     }
     list_response = make_http_call(request_type='post',
                                    url=url,
                                    params=method_args,
                                    headers={
                                        'accept': 'application/json',
                                        'Content-Type': 'application/json'
                                    })
     if list_response['success']:
         return list_response['data']
     else:
         return None
Beispiel #22
0
def registerhook(ctx_obj, url):
    contract = ctx_obj['contract_address']
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, ctx_obj['private_key'])
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": ctx_obj['api_key'],
        "type": "web",
        "contract": contract,
        "web": url
    }
    r = requests.post(url=f'{ctx_obj["internal_api_endpoint"]}/hooks/add',
                      json=method_args,
                      headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if not r['success']:
            click.echo('Failed to register webhook with MaticVigil API...')
        else:
            hook_id = r["data"]["id"]
            click.echo(
                'Succeeded in registering webhook with MaticVigil API...')
            click.echo(f'MaticVigil Hook ID: {hook_id}')
    else:
        click.echo('Failed to register webhook with MaticVigil API...')
Beispiel #23
0
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))
Beispiel #24
0
def test_p12():

    p12filename = "bin/0xea5d262806c5771ae57e8fe4051c91d62b1d67bf.p12"
    with open(p12filename, "rb") as f:

        p12buff = f.read()
        pwd = b"123456"
        (key, cert,
         additional_certificates) = pkcs12.load_key_and_certificates(
             bytes(p12buff), password=pwd, backend=default_backend())
        print("p12 privkey :", key)
        print("p12 privkey size:", key.key_size)
        print("p12 public  bytes:", key.public_key)

        # 用crypto加载p12文件,会有warning "PKCS#12 support in pyOpenSSL is deprecated.
        # You should use the APIs in cryptography."
        crypto_p12 = crypto.load_pkcs12(p12buff, pwd)
        print("crypto_p12: ", crypto_p12)
        print("crypto_p12 privatekey  : ", crypto_p12.get_privatekey())

        # 用cryto可以导出私钥到pem,但目前不能导出到p12
        privatekey = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                            crypto_p12.get_privatekey())
        print("private pem :", privatekey)
        key = SigningKey.from_pem(privatekey)
        print("privkey : ", encode_hex(key.to_string()))
        ac2 = Account.from_key(encode_hex(key.to_string()))
        print("pubkey: ", ac2.publickey)
        print("address: ", ac2.address)
        f.close()
Beispiel #25
0
 def _register_integration(self, url):
     headers = {
         'accept': 'application/json',
         'Content-Type': 'application/json',
         'X-API-KEY': self._api_write_key
     }
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash, self._ev_private_key)
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._ev_private_key,
         "type": "web",
         "contract": self._contract_address,
         "web": url
     }
     reg_webhook_args = dict(
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/add',
         params=method_args,
         headers=headers)
     ev_core_logger.debug('Registering webhook')
     ev_core_logger.debug(reg_webhook_args)
     r = make_http_call(request_type='post', **reg_webhook_args)
     ev_core_logger.debug('Registration response')
     ev_core_logger.debug(r)
     if not r['success']:
         return None
     else:
         hook_id = r["data"]["id"]
         return hook_id
Beispiel #26
0
 def add_contract_monitoring_integration(self,
                                         callback_url,
                                         integration_channel='web'):
     hook_id = self._register_integration(callback_url)
     if not hook_id:
         return None
     if not integration_channel == 'web':
         err_msg = 'Only integrations of type \'web\' are supported by SDK currently'
         ev_core_logger.error(err_msg)
         raise EVBaseException(err_msg)
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address,
         "id": hook_id,
         "action": "set"
     }
     integration_response = make_http_call(
         request_type='post',
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] +
         '/hooks/transactions',
         params=method_args,
         headers={
             'accept': 'application/json',
             'Content-Type': 'application/json'
         })
     return hook_id if integration_response.get('success', False) else None
Beispiel #27
0
def get_signature_recovery_value(message: bytes, signature: Signature,
                                 public_key: PublicKey) -> bytes:
    """
    Obtains the recovery value of a standard ECDSA signature.

    :param message: Signed message
    :param signature: The signature from which the pubkey is recovered
    :param public_key: The public key for verifying the signature
    :param is_prehashed: True if the message is already pre-hashed. Default is False, and message will be hashed with SHA256
    :return: The compressed byte-serialized representation of the recovered public key
    """

    signature = bytes(signature)
    ecdsa_signature_size = 64  # two curve scalars
    if len(signature) != ecdsa_signature_size:
        raise ValueError(
            f"The signature size should be {ecdsa_signature_size} B.")

    hash_ctx = hashes.Hash(hashes.SHA256(), backend=backend)
    hash_ctx.update(message)
    message_hash = hash_ctx.finalize()

    address = canonical_address_from_umbral_key(public_key)
    for v in (0, 1):
        v_byte = bytes([v])
        recovered = to_canonical_address(
            Account.recoverHash(message_hash, signature=signature + v_byte))
        if recovered == address:
            return v_byte
    else:
        raise ValueError(
            "Signature recovery failed. "
            "Either the message, the signature or the public key is not correct"
        )
Beispiel #28
0
def create_account_console(logger: Logger, network: str):
    """Creates an Ethereum account and echoes the details to console."""

    acc = Account.create()
    private_key = to_hex(acc.privateKey)

    if private_key.startswith("0x"):
        # Looks like this behaves differently in different versions,
        # we assume no 0x prefix for private key to distinguish it from addresses
        # and hashes
        private_key = private_key[2:]

    logger.info("Account address: %s", acc.address)
    logger.info("Account private key: %s", private_key)

    config = CONFIG_FILE_TEMPLATE.format(private_key=private_key,
                                         network=network,
                                         address=acc.address)
    config_file_name = "myconfig.ini"

    print()
    print("Create a file {}{}{} and paste in the following content: {}{}{}".
          format(colorama.Fore.LIGHTBLUE_EX, config_file_name,
                 colorama.Fore.RESET, colorama.Fore.LIGHTBLACK_EX, config,
                 colorama.Fore.RESET))
    print()
    print("After this you can run {}sto --config-file={} diagnose{}".format(
        colorama.Fore.LIGHTBLUE_EX, config_file_name, colorama.Fore.RESET))
Beispiel #29
0
 def activate_integration(self, hook_id):
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address,
         "id": hook_id
     }
     integration_response = make_http_call(
         request_type='post',
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/activate',
         params=method_args,
         headers={
             'accept': 'application/json',
             'Content-Type': 'application/json'
         })
     if not integration_response['success']:
         return False
     else:
         return True
Beispiel #30
0
def sign_txn_array(messages, private_key):
    message_dict = {}
    for message in messages:
        signed_message =\
            binascii.hexlify(Account.signHash(message['txn']['sha256'], private_key=private_key)['signature']).decode()
        message_dict[message['id']] = '0x' + signed_message
    return message_dict