def make_key_and_name():
        context = sawtooth_signing.create_context("secp256k1")
        private_key = context.new_random_private_key()
        pubkey = context.get_public_key(private_key)

        key = Key(public_key=pubkey.as_hex(), private_key=private_key.as_hex())
        return key, uuid4().hex
Esempio n. 2
0
async def get_transactor_key(request):
    id_dict = deserialize_api_key(request.app.config.SECRET_KEY, request.token)
    user_id = id_dict.get("id")

    auth_data = await auth_query.fetch_info_by_user_id(
        request.app.config.DB_CONN, user_id)
    encrypted_private_key = auth_data.get("encrypted_private_key")
    private_key = decrypt_private_key(request.app.config.AES_KEY, user_id,
                                      encrypted_private_key)
    hex_private_key = binascii.hexlify(private_key)
    return Key(hex_private_key)
Esempio n. 3
0
async def create_new_user(request):
    required_fields = ["name", "username", "password"]
    utils.validate_fields(required_fields, request.json)

    # Generate keys
    private_key = Secp256k1PrivateKey.new_random()
    txn_key = Key(private_key.as_hex())
    encrypted_private_key = encrypt_private_key(
        request.app.config.AES_KEY, txn_key.public_key, private_key.as_bytes()
    )

    # Build create user transaction
    batch_list = create_user(
        txn_key,
        request.app.config.BATCHER_KEY_PAIR,
        request.json.get("name"),
        request.json.get("username"),
        txn_key.public_key,
        request.json.get("metadata"),
        request.json.get("manager"),
    )

    # Submit transaction and wait for complete
    await utils.send(
        request.app.config.VAL_CONN, batch_list[0], request.app.config.TIMEOUT
    )

    # Save new user in auth table
    hashed_password = hashlib.sha256(
        request.json.get("password").encode("utf-8")
    ).hexdigest()

    auth_entry = {
        "user_id": txn_key.public_key,
        "hashed_password": hashed_password,
        "encrypted_private_key": encrypted_private_key,
        "user_name": request.json.get("username"),
        "email": request.json.get("email"),
    }
    await auth_query.create_auth_entry(request.app.config.DB_CONN, auth_entry)

    # Send back success response
    return create_user_response(request, txn_key.public_key)
import time
import logging
from uuid import uuid4
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
import sawtooth_signing
from sawtooth_signing.secp256k1 import Secp256k1PrivateKey
from rbac.transaction_creation.common import Key

LOGGER = logging.getLogger(__name__)
LOGGER.level = logging.DEBUG
LOGGER.addHandler(logging.StreamHandler(sys.stdout))

BATCHER_PRIVATE_KEY = Secp256k1PrivateKey.new_random().as_hex()
BATCHER_KEY = Key(BATCHER_PRIVATE_KEY)


class IntegrationTestHelper:
    """ A singleton test helper ensuring the Docker containers
    are up and available to be tested against."""

    class __impl:

        __available = False

        def wait_for_containers(self):
            self.__check_containers()

        def __check_containers(self):
            if not self.__available:
Esempio n. 5
0
def load_config(app):  # pylint: disable=too-many-branches
    app.config.update(DEFAULT_CONFIG)
    config_file_path = os.path.join(
        os.path.dirname(os.path.dirname(os.path.realpath(__file__))), CONFIG_FILE
    )
    try:
        app.config.from_pyfile(config_file_path)
    except FileNotFoundError:
        LOGGER.warning("No config.py file found. Falling back on safe defaults.")

    # CLI Options will override config file options
    opts = parse_args(sys.argv[1:])

    if opts.host is not None:
        app.config.HOST = opts.host
    if opts.port is not None:
        app.config.PORT = opts.port

    if opts.validator_host is not None:
        app.config.VALIDATOR_HOST = opts.validator_host
    if opts.validator_port is not None:
        app.config.VALIDATOR_PORT = opts.validator_port
    if opts.timeout is not None:
        app.config.TIMEOUT = opts.timeout

    if opts.db_host is not None:
        app.config.DB_HOST = opts.db_host
    if opts.db_port is not None:
        app.config.DB_PORT = opts.db_port
    if opts.db_name is not None:
        app.config.DB_NAME = opts.db_name

    if opts.debug is not None:
        app.config.DEBUG = opts.debug

    if opts.secret_key is not None:
        app.config.SECRET_KEY = opts.secret_key
    if app.config.SECRET_KEY is None:
        LOGGER.warning(
            """"The API secret key was not provided.
        It should be added to config.py before deploying the app to a production environment.
        Generating an API secret key...
        """
        )
        app.config.SECRET_KEY = generate_random_string(KEY_LENGTH_SECRET)

    if opts.aes_key is not None:
        app.config.AES_KEY = opts.aes_key
    if app.config.AES_KEY is None:
        LOGGER.warning(
            """"The AES key was not provided.
        It should be added to config.py before deploying the app to a production environment.
        Generating an AES key...
        """
        )
        app.config.AES_KEY = "%030x" % random.randrange(16 ** KEY_LENGTH_AES)

    if opts.batcher_private_key is not None:
        app.config.BATCHER_PRIVATE_KEY = opts.batcher_private_key
    if app.config.BATCHER_PRIVATE_KEY is None:
        LOGGER.warning(
            """"Batcher private key was not provided.
        It should be added to config.py before deploying the app to a production environment.
        Generating a Batcher private key...
        """
        )
        app.config.BATCHER_PRIVATE_KEY = binascii.b2a_hex(
            os.urandom(KEY_LENGTH_BATCHER)
        )

    app.config.BATCHER_KEY_PAIR = Key(app.config.BATCHER_PRIVATE_KEY)
Esempio n. 6
0
    def create_user_transaction(self, name, username, metadata):
        txn_private_key = Secp256k1PrivateKey.new_random()
        batch_private_key = Secp256k1PrivateKey.new_random()

        txn_key = Key(txn_private_key.as_hex())
        batch_key = Key(batch_private_key.as_hex())

        batchlist, sig = create_user(
            txn_key, batch_key, name, username, txn_key.public_key, metadata
        )

        self.assertEqual(type(sig), str)
        self.assertEqual(type(batchlist), batch_pb2.BatchList)

        self.assertEqual(len(sig), SIGNATURE_LENGTH)
        self.assertTrue(SIGNATURE_PATTERN.match(sig))

        batch_count = 0
        for batch in batchlist.batches:
            batch_count += 1
            self.assertEqual(type(batch), batch_pb2.Batch)
            self.assertEqual(type(batch.header_signature), str)
            self.assertEqual(len(batch.header_signature), SIGNATURE_LENGTH)
            self.assertTrue(SIGNATURE_PATTERN.match(batch.header_signature))

            trans_count = 0
            for transaction in batch.transactions:
                trans_count += 1
                self.assertEqual(type(transaction.header), bytes)
                self.assertEqual(type(transaction.header_signature), str)
                self.assertEqual(type(transaction.payload), bytes)

                self.assertEqual(len(transaction.header_signature), SIGNATURE_LENGTH)
                self.assertTrue(SIGNATURE_PATTERN.match(transaction.header_signature))

                header = transaction_pb2.TransactionHeader()
                header.ParseFromString(transaction.header)

                self.assertEqual(type(header), transaction_pb2.TransactionHeader)
                self.assertEqual(header.family_name, addresser.FAMILY_NAME)
                self.assertEqual(header.family_version, addresser.FAMILY_VERSION)
                self.assertEqual(header.batcher_public_key, batch_key.public_key)
                self.assertEqual(header.signer_public_key, txn_key.public_key)

                self.assertEqual(len(header.payload_sha512), SIGNATURE_LENGTH)
                self.assertTrue(SIGNATURE_PATTERN.match(header.payload_sha512))

                input_count = 0
                for address in header.inputs:
                    input_count += 1
                    self.assertEqual(type(address), str)
                    self.assertEqual(len(address), addresser.ADDRESS_LENGTH)
                    self.assertEqual(
                        addresser.address_is(address), addresser.AddressSpace.USER
                    )

                self.assertEqual(input_count, 1)

                output_count = 0
                for address in header.outputs:
                    output_count += 1
                    self.assertEqual(type(address), str)
                    self.assertEqual(len(address), addresser.ADDRESS_LENGTH)
                    self.assertEqual(
                        addresser.address_is(address), addresser.AddressSpace.USER
                    )

                self.assertEqual(output_count, 1)

                payload = rbac_payload_pb2.RBACPayload()
                payload.ParseFromString(transaction.payload)

                self.assertEqual(type(payload), rbac_payload_pb2.RBACPayload)
                self.assertEqual(
                    payload.message_type, rbac_payload_pb2.RBACPayload.CREATE_USER
                )
                self.assertEqual(type(payload.content), bytes)

                user = user_transaction_pb2.CreateUser()
                user.ParseFromString(payload.content)

                self.assertEqual(type(user), user_transaction_pb2.CreateUser)
                self.assertEqual(user.name, name)
                self.assertEqual(user.user_name, username)
                self.assertEqual(type(user.user_id), str)
                self.assertEqual(user.user_id, txn_key.public_key)

            self.assertEqual(trans_count, 1)

        self.assertEqual(batch_count, 1)