当前位置: 首页>>代码示例>>Python>>正文


Python CryptoFactory.get_public_key方法代码示例

本文整理汇总了Python中sawtooth_signing.CryptoFactory.get_public_key方法的典型用法代码示例。如果您正苦于以下问题:Python CryptoFactory.get_public_key方法的具体用法?Python CryptoFactory.get_public_key怎么用?Python CryptoFactory.get_public_key使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sawtooth_signing.CryptoFactory的用法示例。


在下文中一共展示了CryptoFactory.get_public_key方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_account

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]
async def create_account(request):
    """Creates a new Account and corresponding authorization token"""
    required_fields = ['email', 'password']
    common.validate_fields(required_fields, request.json)

    private_key = request.app.config.CONTEXT.new_random_private_key()
    signer = CryptoFactory(request.app.config.CONTEXT).new_signer(private_key)
    public_key = signer.get_public_key().as_hex()

    auth_entry = _create_auth_dict(
        request, public_key, private_key.as_hex())
    await auth_query.create_auth_entry(request.app.config.DB_CONN, auth_entry)

    account = _create_account_dict(request.json, public_key)

    batches, batch_id = transaction_creation.create_account(
        txn_key=signer,
        batch_key=request.app.config.SIGNER,
        label=account.get('label'),
        description=account.get('description'))

    await messaging.send(
        request.app.config.VAL_CONN,
        request.app.config.TIMEOUT,
        batches)

    try:
        await messaging.check_batch_status(
            request.app.config.VAL_CONN, batch_id)
    except (ApiBadRequest, ApiInternalError) as err:
        await auth_query.remove_auth_entry(
            request.app.config.DB_CONN, request.json.get('email'))
        raise err

    token = common.generate_auth_token(
        request.app.config.SECRET_KEY,
        account.get('email'),
        public_key)

    return response.json(
        {
            'authorization': token,
            'account': account
        })
开发者ID:delventhalz,项目名称:sawtooth-mktplace,代码行数:46,代码来源:accounts.py

示例2: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]

#.........这里部分代码省略.........

        headers = {}

        if content_type is not None:
            headers['Content-Type'] = content_type

        try:
            if data is not None:
                result = requests.post(url, headers=headers, data=data)
            else:
                result = requests.get(url, headers=headers)

            if result.status_code == 404:
                raise IntkeyClientException("No such key: {}".format(name))

            elif not result.ok:
                raise IntkeyClientException("Error {}: {}".format(
                    result.status_code, result.reason))

        except requests.ConnectionError as err:
            raise IntkeyClientException(
                'Failed to connect to REST API: {}'.format(err))

        except BaseException as err:
            raise IntkeyClientException(err)

        return result.text

    def _send_transaction(self, verb, name, value, wait=None):
        payload = cbor.dumps({
            'Verb': verb,
            'Name': name,
            'Value': value,
        })

        # Construct the address
        address = self._get_address(name)

        header = TransactionHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            family_name="intkey",
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_sha512(payload),
            batcher_public_key=self._signer.get_public_key().as_hex(),
            nonce=hex(random.randint(0, 2**64))
        ).SerializeToString()

        signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=signature
        )

        batch_list = self._create_batch_list([transaction])
        batch_id = batch_list.batches[0].header_signature

        if wait and wait > 0:
            wait_time = 0
            start_time = time.time()
            response = self._send_request(
                "batches", batch_list.SerializeToString(),
                'application/octet-stream',
            )
            while wait_time < wait:
                status = self._get_status(
                    batch_id,
                    wait - int(wait_time),
                )
                wait_time = time.time() - start_time

                if status != 'PENDING':
                    return response

            return response

        return self._send_request(
            "batches", batch_list.SerializeToString(),
            'application/octet-stream',
        )

    def _create_batch_list(self, transactions):
        transaction_signatures = [t.header_signature for t in transactions]

        header = BatchHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            transaction_ids=transaction_signatures
        ).SerializeToString()

        signature = self._signer.sign(header)

        batch = Batch(
            header=header,
            transactions=transactions,
            header_signature=signature)
        return BatchList(batches=[batch])
开发者ID:cianx,项目名称:sawtooth-core,代码行数:104,代码来源:intkey_client.py

示例3: Transactor

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]
class Transactor(object):
    def __init__(self, name, rest_endpoint):
        """
        Args:
            name (str): An identifier for this Transactor
            rest_endpoint (str): The rest api that this Transactor will
                communicate with.
        """

        self.name = name
        self._rest_endpoint = rest_endpoint \
            if rest_endpoint.startswith("http://") \
            else "http://{}".format(rest_endpoint)
        with open('/root/.sawtooth/keys/{}.priv'.format(name)) as priv_file:
            private_key = Secp256k1PrivateKey.from_hex(
                priv_file.read().strip('\n'))
        self._signer = CryptoFactory(create_context('secp256k1')) \
            .new_signer(private_key)
        self._factories = {}
        self._client = RestClient(url=self._rest_endpoint)

        self._add_transaction_family_factory(Families.INTKEY)
        self._add_transaction_family_factory(Families.XO)

    @property
    def public_key(self):
        return self._signer.get_public_key().as_hex()

    def _add_transaction_family_factory(self, family_name):
        """Add a MessageFactory for the specified family.

        Args:
            family_name (Families): One of the Enum values representing
                transaction families.
        """

        family_config = FAMILY_CONFIG[family_name]
        self._factories[family_name] = MessageFactory(
            family_name=family_config['family_name'],
            family_version=family_config['family_version'],
            namespace=family_config['namespace'],
            signer=self._signer)

    def create_txn(self, family_name, batcher=None):
        unique_value = uuid4().hex[:20]
        encoder = TRANSACTION_ENCODER[family_name]['encoder']
        payload = encoder(
            TRANSACTION_ENCODER[family_name]['payload_func'](unique_value))

        address = TRANSACTION_ENCODER[family_name]['address_func'](
            unique_value)

        return self._factories[family_name].create_transaction(
            payload=payload,
            inputs=[address],
            outputs=[address],
            deps=[],
            batcher=batcher)

    def create_batch(self, family_name, count=1):
        transactions = [self.create_txn(family_name) for _ in range(count)]
        return self.batch_transactions(family_name, transactions=transactions)

    def batch_transactions(self, family_name, transactions):
        return self._factories[family_name].create_batch(
            transactions=transactions)

    def send(self, family_name, transactions=None):
        if not transactions:
            batch_list = self.create_batch(family_name)
        else:
            batch_list = self.batch_transactions(
                family_name=family_name,
                transactions=transactions)

        self._client.send_batches(batch_list=batch_list)

    def set_public_key_for_role(self, policy, role, permit_keys, deny_keys):
        permits = ["PERMIT_KEY {}".format(key) for key in permit_keys]
        denies = ["DENY_KEY {}".format(key) for key in deny_keys]
        self._run_identity_commands(policy, role, denies + permits)

    def _run_identity_commands(self, policy, role, rules):
        subprocess.run(
            ['sawtooth', 'identity', 'policy', 'create',
             '-k', '/root/.sawtooth/keys/{}.priv'.format(self.name),
             '--wait', '15',
             '--url', self._rest_endpoint, policy, *rules],
            check=True)
        subprocess.run(
            ['sawtooth', 'identity', 'role', 'create',
             '-k', '/root/.sawtooth/keys/{}.priv'.format(self.name),
             '--wait', '15',
             '--url', self._rest_endpoint, role, policy],
            check=True)
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:97,代码来源:test_transactor_permissioning.py

示例4: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]
class BattleshipClient:

    def __init__(self, base_url, keyfile, wait=None):
        """
        Member variables:
            _base_url
            _private_key
            _public_key
            _transaction_family
            _family_version
            _wait
        """
        self._base_url = base_url

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise IOError("Failed to read keys: {}.".format(str(err)))

        try:
            private_key = Secp256k1PrivateKey.from_hex(private_key_str)
        except ParseError as e:
            raise BattleshipException(
                'Unable to load private key: {}'.format(str(e)))

        self._signer = CryptoFactory(
            create_context('secp256k1')).new_signer(private_key)

        self._transaction_family = "battleship"
        self._family_version = "1.0"
        self._wait = wait

    def _send_battleship_txn(self, update):
        """The client needs to have the same
            defaults as the Transaction subclass
            before it is signed inside sendtxn
        """
        if 'Name' not in update:
            raise BattleshipException('Game name required')
        if 'Action' not in update:
            update['Action'] = None
        if 'Ships' not in update:
            update['Ships'] = None
        if update['Action'] == 'JOIN':
            if 'Board' not in update:
                update['Board'] = None
        if update['Action'] == 'FIRE':
            if 'Column' not in update:
                update['Column'] = None
            if 'Row' not in update:
                update['Row'] = None

        payload = json.dumps(update).encode()
        address = self._get_address(update['Name'])

        header = TransactionHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            family_name=self._transaction_family,
            family_version=self._family_version,
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=self._sha512(payload),
            batcher_public_key=self.signer.get_public_key().as_hex(),
            nonce=hex(random.randint(0, 2**64))
        ).SerializeToString()

        signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=signature
        )

        batch_list = self._create_batch_list([transaction])
        batch_id = batch_list.batches[0].header_signature

        if self._wait and self._wait > 0:
            wait_time = 0
            start_time = time.time()
            response = self._send_request(
                "batches", batch_list.SerializeToString(),
                'application/octet-stream'
            )
            while wait_time < self._wait:
                status = self._get_status(
                    batch_id,
                    self._wait - int(wait_time)
                )
                wait_time = time.time() - start_time

                if status != 'PENDING':
                    return response

            return response

        return self._send_request(
            "batches", batch_list.SerializeToString(),
#.........这里部分代码省略.........
开发者ID:dcmiddle,项目名称:sawtooth-core,代码行数:103,代码来源:battleship_client.py

示例5: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]

#.........这里部分代码省略.........
        try:
            if data is not None:
                result = requests.post(url, headers=headers, data=data)
            else:
                result = requests.get(url, headers=headers)

            if result.status_code == 404:
                raise XoException("No such game: {}".format(name))

            elif not result.ok:
                raise XoException("Error {}: {}".format(
                    result.status_code, result.reason))

        except requests.ConnectionError as err:
            raise XoException(
                'Failed to connect to {}: {}'.format(url, str(err)))

        except BaseException as err:
            raise XoException(err)

        return result.text

    def _send_xo_txn(self,
                     name,
                     action,
                     space="",
                     wait=None,
                     auth_user=None,
                     auth_password=None):
        # Serialization is just a delimited utf-8 encoded string
        payload = ",".join([name, action, str(space)]).encode()

        # Construct the address
        address = self._get_address(name)

        header = TransactionHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            family_name="xo",
            family_version="1.0",
            inputs=[address],
            outputs=[address],
            dependencies=[],
            payload_sha512=_sha512(payload),
            batcher_public_key=self._signer.get_public_key().as_hex(),
            nonce=time.time().hex().encode()
        ).SerializeToString()

        signature = self._signer.sign(header)

        transaction = Transaction(
            header=header,
            payload=payload,
            header_signature=signature
        )

        batch_list = self._create_batch_list([transaction])
        batch_id = batch_list.batches[0].header_signature

        if wait and wait > 0:
            wait_time = 0
            start_time = time.time()
            response = self._send_request(
                "batches", batch_list.SerializeToString(),
                'application/octet-stream',
                auth_user=auth_user,
                auth_password=auth_password)
            while wait_time < wait:
                status = self._get_status(
                    batch_id,
                    wait - int(wait_time),
                    auth_user=auth_user,
                    auth_password=auth_password)
                wait_time = time.time() - start_time

                if status != 'PENDING':
                    return response

            return response

        return self._send_request(
            "batches", batch_list.SerializeToString(),
            'application/octet-stream',
            auth_user=auth_user,
            auth_password=auth_password)

    def _create_batch_list(self, transactions):
        transaction_signatures = [t.header_signature for t in transactions]

        header = BatchHeader(
            signer_public_key=self._signer.get_public_key().as_hex(),
            transaction_ids=transaction_signatures
        ).SerializeToString()

        signature = self._signer.sign(header)

        batch = Batch(
            header=header,
            transactions=transactions,
            header_signature=signature)
        return BatchList(batches=[batch])
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:104,代码来源:xo_client.py

示例6: create_context

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import get_public_key [as 别名]
from sawtooth_sdk.protobuf.transaction_pb2 import TransactionHeader
from sawtooth_sdk.protobuf.transaction_pb2 import Transaction
import sawtooth_sdk
from sawtooth_signing import create_context
from sawtooth_signing import CryptoFactory
from sawtooth_sdk.protobuf.batch_pb2 import BatchHeader
from sawtooth_sdk.protobuf.batch_pb2 import Batch
from sawtooth_sdk.protobuf.batch_pb2 import BatchList

#Creates a signer who will sign the tx and validate
#its identity in front of the validator
context = create_context('secp256k1')
private_key = context.new_random_private_key()

signer = CryptoFactory(context).new_signer(private_key)
print("SIGNER ES: {}".format(signer.get_public_key().as_hex()))

#Checks for correct amount of parameters
if len(sys.argv) != 3:
	print("Use: ./send_tx NumOfBatches NumOfTxPerBatch")
	sys.exit(1)

NUM_BATCHES = int(sys.argv[1])
NUM_TX_PER_BATCH = int(sys.argv[2])

#Generate the payload of the tx
#Every family has a structure to follow
#Uses the cbor format

N = 10
开发者ID:afuentesconwet,项目名称:sawtooth_scripts,代码行数:32,代码来源:send_tx.py


注:本文中的sawtooth_signing.CryptoFactory.get_public_key方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。