github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/validator/sawtooth_validator/server/keys.py (about)

     1  # Copyright 2016, 2017 Intel Corporation
     2  #
     3  # Licensed under the Apache License, Version 2.0 (the "License");
     4  # you may not use this file except in compliance with the License.
     5  # You may obtain a copy of the License at
     6  #
     7  #     http://www.apache.org/licenses/LICENSE-2.0
     8  #
     9  # Unless required by applicable law or agreed to in writing, software
    10  # distributed under the License is distributed on an "AS IS" BASIS,
    11  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  # See the License for the specific language governing permissions and
    13  # limitations under the License.
    14  # ------------------------------------------------------------------------------
    15  
    16  import logging
    17  import os
    18  
    19  import sawtooth_signing as signing
    20  from sawtooth_signing import CryptoFactory
    21  from sawtooth_signing.secp256k1 import Secp256k1PrivateKey
    22  from sawtooth_validator.exceptions import LocalConfigurationError
    23  
    24  LOGGER = logging.getLogger(__name__)
    25  
    26  
    27  def load_identity_signer(key_dir, key_name):
    28      """Loads a private key from the key directory, based on a validator's
    29      identity.
    30  
    31      Args:
    32          key_dir (str): The path to the key directory.
    33          key_name (str): The name of the key to load.
    34  
    35      Returns:
    36          Signer: the cryptographic signer for the key
    37      """
    38      key_path = os.path.join(key_dir, '{}.priv'.format(key_name))
    39  
    40      if not os.path.exists(key_path):
    41          raise LocalConfigurationError(
    42              "No such signing key file: {}".format(key_path))
    43      if not os.access(key_path, os.R_OK):
    44          raise LocalConfigurationError(
    45              "Key file is not readable: {}".format(key_path))
    46  
    47      LOGGER.info('Loading signing key: %s', key_path)
    48      try:
    49          with open(key_path, 'r') as key_file:
    50              private_key_str = key_file.read().strip()
    51      except IOError as e:
    52          raise LocalConfigurationError(
    53              "Could not load key file: {}".format(str(e)))
    54  
    55      try:
    56          private_key = Secp256k1PrivateKey.from_hex(private_key_str)
    57      except signing.ParseError as e:
    58          raise LocalConfigurationError(
    59              "Invalid key in file {}: {}".format(key_path, str(e)))
    60  
    61      context = signing.create_context('secp256k1')
    62      crypto_factory = CryptoFactory(context)
    63      return crypto_factory.new_signer(private_key)