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


Python CryptoFactory.sign方法代码示例

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


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

示例1: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import sign [as 别名]
class IntkeyClient:
    def __init__(self, url, keyfile=None):
        self.url = url

        if keyfile is not None:
            try:
                with open(keyfile) as fd:
                    private_key_str = fd.read().strip()
                    fd.close()
            except OSError as err:
                raise IntkeyClientException(
                    'Failed to read private key: {}'.format(str(err)))

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

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

    def set(self, name, value, wait=None):
        return self._send_transaction('set', name, value, wait=wait)

    def inc(self, name, value, wait=None):
        return self._send_transaction('inc', name, value, wait=wait)

    def dec(self, name, value, wait=None):
        return self._send_transaction('dec', name, value, wait=wait)

    def list(self):
        result = self._send_request(
            "state?address={}".format(
                self._get_prefix()))

        try:
            encoded_entries = yaml.safe_load(result)["data"]

            return [
                cbor.loads(base64.b64decode(entry["data"]))
                for entry in encoded_entries
            ]

        except BaseException:
            return None

    def show(self, name):
        address = self._get_address(name)

        result = self._send_request("state/{}".format(address), name=name,)

        try:
            return cbor.loads(
                base64.b64decode(
                    yaml.safe_load(result)["data"]))[name]

        except BaseException:
            return None

    def _get_status(self, batch_id, wait):
        try:
            result = self._send_request(
                'batch_statuses?id={}&wait={}'.format(batch_id, wait),)
            return yaml.safe_load(result)['data'][0]['status']
        except BaseException as err:
            raise IntkeyClientException(err)

    def _get_prefix(self):
        return _sha512('intkey'.encode('utf-8'))[0:6]

    def _get_address(self, name):
        prefix = self._get_prefix()
        game_address = _sha512(name.encode('utf-8'))[64:]
        return prefix + game_address

    def _send_request(self, suffix, data=None, content_type=None, name=None):
        if self.url.startswith("http://"):
            url = "{}/{}".format(self.url, suffix)
        else:
            url = "http://{}/{}".format(self.url, suffix)

        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))

#.........这里部分代码省略.........
开发者ID:cianx,项目名称:sawtooth-core,代码行数:103,代码来源:intkey_client.py

示例2: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import sign [as 别名]
class XoClient:
    def __init__(self, base_url, keyfile=None):

        self._base_url = base_url

        if keyfile is None:
            self._signer = None
            return

        try:
            with open(keyfile) as fd:
                private_key_str = fd.read().strip()
        except OSError as err:
            raise XoException(
                'Failed to read private key {}: {}'.format(
                    keyfile, str(err)))

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

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

    def create(self, name, wait=None, auth_user=None, auth_password=None):
        return self._send_xo_txn(
            name,
            "create",
            wait=wait,
            auth_user=auth_user,
            auth_password=auth_password)

    def delete(self, name, wait=None, auth_user=None, auth_password=None):
        return self._send_xo_txn(
            name,
            "delete",
            wait=wait,
            auth_user=auth_user,
            auth_password=auth_password)

    def take(self, name, space, wait=None, auth_user=None, auth_password=None):
        return self._send_xo_txn(
            name,
            "take",
            space,
            wait=wait,
            auth_user=auth_user,
            auth_password=auth_password)

    def list(self, auth_user=None, auth_password=None):
        xo_prefix = self._get_prefix()

        result = self._send_request(
            "state?address={}".format(xo_prefix),
            auth_user=auth_user,
            auth_password=auth_password)

        try:
            encoded_entries = yaml.safe_load(result)["data"]

            return [
                base64.b64decode(entry["data"]) for entry in encoded_entries
            ]

        except BaseException:
            return None

    def show(self, name, auth_user=None, auth_password=None):
        address = self._get_address(name)

        result = self._send_request(
            "state/{}".format(address),
            name=name,
            auth_user=auth_user,
            auth_password=auth_password)
        try:
            return base64.b64decode(yaml.safe_load(result)["data"])

        except BaseException:
            return None

    def _get_status(self, batch_id, wait, auth_user=None, auth_password=None):
        try:
            result = self._send_request(
                'batch_statuses?id={}&wait={}'.format(batch_id, wait),
                auth_user=auth_user,
                auth_password=auth_password)
            return yaml.safe_load(result)['data'][0]['status']
        except BaseException as err:
            raise XoException(err)

    def _get_prefix(self):
        return _sha512('xo'.encode('utf-8'))[0:6]

    def _get_address(self, name):
        xo_prefix = self._get_prefix()
        game_address = _sha512(name.encode('utf-8'))[0:64]
        return xo_prefix + game_address
#.........这里部分代码省略.........
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:103,代码来源:xo_client.py

示例3: __init__

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import sign [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

示例4: sha512

# 需要导入模块: from sawtooth_signing import CryptoFactory [as 别名]
# 或者: from sawtooth_signing.CryptoFactory import sign [as 别名]
			family_version='1.0',
			inputs=[tx_addr[i][j]],
			outputs=[tx_addr[i][j]],
			signer_public_key = signer.get_public_key().as_hex(),
			batcher_public_key = signer.get_public_key().as_hex(),
			dependencies=[],
			payload_sha512 = sha512(payload_bytes_arr[i][j]).hexdigest()
		).SerializeToString()
	for j in range(NUM_TX_PER_BATCH)
	] for i in range(NUM_BATCHES)
]

#Signer signs the header:
signature_arr = [
	[
		signer.sign(tx_header_arr[i][j])
	for j in range(NUM_TX_PER_BATCH)
	] for i in range(NUM_BATCHES)
]

#Generate an array with all the transactions
tx_arr= [
		[Transaction(
			header=tx_header_arr[i][j],
			header_signature=signature_arr[i][j],
			payload = payload_bytes_arr[i][j]
			)
		for j in range(NUM_TX_PER_BATCH)
		]
	for i in range(NUM_BATCHES)
	]
开发者ID:afuentesconwet,项目名称:sawtooth_scripts,代码行数:33,代码来源:send_tx.py


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