• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sawtooth_signing.create_context函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sawtooth_signing.create_context函数的典型用法代码示例。如果您正苦于以下问题:Python create_context函数的具体用法?Python create_context怎么用?Python create_context使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: __init__

    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
开发者ID:dcmiddle,项目名称:sawtooth-core,代码行数:30,代码来源:battleship_client.py


示例2: _read_signer

def _read_signer(key_filename):
    """Reads the given file as a hex key.

    Args:
        key_filename: The filename where the key is stored. If None,
            defaults to the default key for the current user.

    Returns:
        Signer: the signer

    Raises:
        CliException: If unable to read the file.
    """
    filename = key_filename
    if filename is None:
        filename = os.path.join(os.path.expanduser('~'),
                                '.sawtooth',
                                'keys',
                                getpass.getuser() + '.priv')

    try:
        with open(filename, 'r') as key_file:
            signing_key = key_file.read().strip()
    except IOError as e:
        raise CliException('Unable to read key file: {}'.format(str(e)))

    try:
        private_key = Secp256k1PrivateKey.from_hex(signing_key)
    except ParseError as e:
        raise CliException('Unable to read key in file: {}'.format(str(e)))

    context = create_context('secp256k1')
    crypto_factory = CryptoFactory(context)
    return crypto_factory.new_signer(private_key)
开发者ID:jjason,项目名称:sawtooth-core,代码行数:34,代码来源:sawset.py


示例3: do_populate

def do_populate(args):
    context = create_context('secp256k1')
    signer = CryptoFactory(context).new_signer(
        context.new_random_private_key())

    words = generate_word_list(args.pool_size)

    batches = []
    total_txn_count = 0
    txns = []
    for i in range(0, len(words)):
        txn = create_intkey_transaction(
            verb='set',
            name=words[i],
            value=random.randint(9000, 100000),
            signer=signer)
        total_txn_count += 1
        txns.append(txn)

    batch = create_batch(
        transactions=txns,
        signer=signer)

    batches.append(batch)

    batch_list = batch_pb2.BatchList(batches=batches)

    print("Writing to {}...".format(args.output))
    with open(args.output, "wb") as fd:
        fd.write(batch_list.SerializeToString())
开发者ID:cianx,项目名称:sawtooth-core,代码行数:30,代码来源:populate.py


示例4: __init__

    def __init__(self, delegate, args):
        super(IntKeyWorkload, self).__init__(delegate, args)
        self._auth_info = args.auth_info
        self._urls = []
        self._pending_batches = {}
        self._lock = threading.Lock()
        self._delegate = delegate
        self._deps = {}
        context = create_context('secp256k1')
        crypto_factory = CryptoFactory(context=context)
        if args.key_file is not None:
            try:
                with open(args.key_file, 'r') as infile:
                    signing_key = infile.read().strip()
                private_key = Secp256k1PrivateKey.from_hex(signing_key)

                self._signer = crypto_factory.new_signer(
                    private_key=private_key)
            except ParseError as pe:
                raise IntKeyCliException(str(pe))
            except IOError as ioe:
                raise IntKeyCliException(str(ioe))
        else:
            self._signer = crypto_factory.new_signer(
                context.new_random_private_key())
开发者ID:cianx,项目名称:sawtooth-core,代码行数:25,代码来源:intkey_workload.py


示例5: setUp

    def setUp(self):
        self.dir = tempfile.mkdtemp()
        self.block_db = NativeLmdbDatabase(
            os.path.join(self.dir, 'block.lmdb'),
            BlockStore.create_index_configuration())
        self.block_store = BlockStore(self.block_db)
        self.block_manager = BlockManager()
        self.block_manager.add_commit_store(self.block_store)
        self.gossip = MockGossip()
        self.completer = Completer(
            block_manager=self.block_manager,
            transaction_committed=self.block_store.has_transaction,
            get_committed_batch_by_id=self.block_store.get_batch,
            get_committed_batch_by_txn_id=(
                self.block_store.get_batch_by_transaction
            ),
            get_chain_head=lambda: self.block_store.chain_head,
            gossip=self.gossip)
        self.completer.set_on_block_received(self._on_block_received)
        self.completer.set_on_batch_received(self._on_batch_received)
        self._has_block_value = True

        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        crypto_factory = CryptoFactory(context)
        self.signer = crypto_factory.new_signer(private_key)

        self.blocks = []
        self.batches = []
开发者ID:cianx,项目名称:sawtooth-core,代码行数:29,代码来源:test.py


示例6: do_populate

def do_populate(batches, keys):
    context = create_context('secp256k1')
    private_key = context.new_random_private_key()
    crypto_factory = CryptoFactory(context)
    signer = crypto_factory.new_signer(private_key)

    total_txn_count = 0
    txns = []
    for i in range(0, len(keys)):
        name = list(keys)[i]
        txn = create_intkey_transaction(
            verb='set',
            name=name,
            value=random.randint(9000, 100000),
            deps=[],
            signer=signer)
        total_txn_count += 1
        txns.append(txn)
        # Establish the signature of the txn associated with the word
        # so we can create good dependencies later
        keys[name] = txn.header_signature

    batch = create_batch(
        transactions=txns,
        signer=signer)

    batches.append(batch)
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:27,代码来源:create_batch.py


示例7: is_valid_batch

def is_valid_batch(batch):
    # validate batch signature
    header = BatchHeader()
    header.ParseFromString(batch.header)

    context = create_context('secp256k1')
    public_key = Secp256k1PublicKey.from_hex(header.signer_public_key)
    if not context.verify(batch.header_signature,
                          batch.header,
                          public_key):
        LOGGER.debug("batch failed signature validation: %s",
                     batch.header_signature)
        return False

    # validate all transactions in batch
    for txn in batch.transactions:
        if not is_valid_transaction(txn):
            return False

        txn_header = TransactionHeader()
        txn_header.ParseFromString(txn.header)
        if txn_header.batcher_public_key != header.signer_public_key:
            LOGGER.debug("txn batcher public_key does not match signer"
                         "public_key for batch: %s txn: %s",
                         batch.header_signature,
                         txn.header_signature)
            return False

    return True
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:29,代码来源:signature_verifier.py


示例8: setUpClass

    def setUpClass(cls):
        super().setUpClass()
        context = create_context('secp256k1')
        private_key = Secp256k1PrivateKey.from_hex(PRIVATE)
        signer = CryptoFactory(context).new_signer(private_key)

        cls.factory = ValidatorRegistryMessageFactory(
            signer=signer)
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:8,代码来源:test_tp_validator_registry.py


示例9: _create_key

    def _create_key(self, key_name='validator.priv'):
        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        priv_file = os.path.join(self._temp_dir, key_name)
        with open(priv_file, 'w') as priv_fd:
            priv_fd.write(private_key.as_hex())

        return context.get_public_key(private_key).as_hex()
开发者ID:jjason,项目名称:sawtooth-core,代码行数:8,代码来源:tests.py


示例10: __init__

 def __init__(self, delegate, args):
     super(NoopWorkload, self).__init__(delegate, args)
     self._urls = []
     self._lock = threading.Lock()
     self._delegate = delegate
     context = create_context('secp256k1')
     self._signer = CryptoFactory(context).new_signer(
         context.new_random_private_key())
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:8,代码来源:workload.py


示例11: load_config

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.py')
    try:
        app.config.from_pyfile(config_file_path)
    except FileNotFoundError:
        LOGGER.warning("No config file provided")

    # 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.timeout is not None:
        app.config.TIMEOUT = opts.timeout

    if opts.validator is not None:
        app.config.VALIDATOR_URL = opts.validator
    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.exception("API secret key was not provided")
        sys.exit(1)

    if opts.aes_key is not None:
        app.config.AES_KEY = opts.aes_key
    if app.config.AES_KEY is None:
        LOGGER.exception("AES key was not provided")
        sys.exit(1)

    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.exception("Batcher private key was not provided")
        sys.exit(1)
    try:
        private_key = Secp256k1PrivateKey.from_hex(
            app.config.BATCHER_PRIVATE_KEY)
    except ParseError as err:
        LOGGER.exception('Unable to load private key: %s', str(err))
        sys.exit(1)
    app.config.CONTEXT = create_context('secp256k1')
    app.config.SIGNER = CryptoFactory(
        app.config.CONTEXT).new_signer(private_key)
开发者ID:delventhalz,项目名称:sawtooth-mktplace,代码行数:58,代码来源:main.py


示例12: __init__

    def __init__(self, rest_endpoint):
        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        self.priv_key = private_key.as_hex()
        self.pub_key = context.get_public_key(private_key).as_hex()

        self._priv_key_file = os.path.join("/tmp", uuid4().hex[:20])
        with open(self._priv_key_file, mode='w') as out:
            out.write(self.priv_key)

        self._rest_endpoint = rest_endpoint
开发者ID:delventhalz,项目名称:sawtooth-core,代码行数:11,代码来源:test_network_permissioning.py


示例13: setUp

 def setUp(self):
     context = create_context('secp256k1')
     crypto_factory = CryptoFactory(context)
     private_key = context.new_random_private_key()
     self.signer = crypto_factory.new_signer(private_key)
     self._identity_view_factory = MockIdentityViewFactory()
     self.permissions = {}
     self._identity_cache = IdentityCache(
         self._identity_view_factory)
     self.permission_verifier = \
         PermissionVerifier(
             permissions=self.permissions,
             current_root_func=self._current_root_func,
             identity_cache=self._identity_cache)
开发者ID:jjason,项目名称:sawtooth-core,代码行数:14,代码来源:tests.py


示例14: test_deserialized_wait_certificate

    def test_deserialized_wait_certificate(self):
        wait_timer = \
            EnclaveWaitTimer(
                validator_address='1600 Pennsylvania Avenue NW',
                duration=3.14159,
                previous_certificate_id='Smart, Maxwell Smart',
                local_mean=2.71828)

        wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_with_wait_timer(
                wait_timer=wait_timer,
                nonce='Eeny, meeny, miny, moe.',
                block_hash='Indigestion. Pepto Bismol.')

        serialized = wait_certificate.serialize()
        private_key = self._create_random_key()
        wait_certificate.signature = \
            create_context('secp256k1').sign(serialized.encode(), private_key)

        copy_wait_certificate = \
            EnclaveWaitCertificate.wait_certificate_from_serialized(
                serialized,
                wait_certificate.signature)

        self.assertAlmostEqual(
            wait_certificate.request_time,
            copy_wait_certificate.request_time)
        self.assertAlmostEqual(
            wait_certificate.duration,
            copy_wait_certificate.duration)
        self.assertEqual(
            wait_certificate.previous_certificate_id,
            copy_wait_certificate.previous_certificate_id)
        self.assertAlmostEqual(
            wait_certificate.local_mean,
            copy_wait_certificate.local_mean)
        self.assertEqual(
            wait_certificate.validator_address,
            copy_wait_certificate.validator_address)
        self.assertEqual(
            wait_certificate.nonce,
            copy_wait_certificate.nonce)
        self.assertEqual(
            wait_certificate.block_hash,
            copy_wait_certificate.block_hash)
        self.assertEqual(
            wait_certificate.signature,
            copy_wait_certificate.signature)

        self.assertEqual(serialized, copy_wait_certificate.serialize())
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:50,代码来源:test_enclave_wait_certificate.py


示例15: __init__

    def __init__(self, with_genesis=True):
        self.block_sender = MockBlockSender()
        self.batch_sender = MockBatchSender()
        self.dir = tempfile.mkdtemp()
        self.block_db = NativeLmdbDatabase(
            os.path.join(self.dir, 'block.lmdb'),
            BlockStore.create_index_configuration())
        self.block_store = BlockStore(self.block_db)
        self.block_cache = BlockCache(self.block_store)
        self.state_db = NativeLmdbDatabase(
            os.path.join(self.dir, "merkle.lmdb"),
            MerkleDatabase.create_index_configuration())

        self.state_view_factory = NativeStateViewFactory(self.state_db)

        self.block_manager = BlockManager()
        self.block_manager.add_commit_store(self.block_store)

        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        crypto_factory = CryptoFactory(context)
        self.signer = crypto_factory.new_signer(private_key)

        identity_private_key = context.new_random_private_key()
        self.identity_signer = crypto_factory.new_signer(identity_private_key)
        chain_head = None
        if with_genesis:
            self.genesis_block = self.generate_genesis_block()
            chain_head = self.genesis_block
            self.block_manager.put([chain_head.block])
            self.block_manager.persist(
                chain_head.block.header_signature,
                "commit_store")

        self.block_publisher = BlockPublisher(
            block_manager=self.block_manager,
            transaction_executor=MockTransactionExecutor(),
            transaction_committed=self.block_store.has_transaction,
            batch_committed=self.block_store.has_batch,
            state_view_factory=self.state_view_factory,
            block_sender=self.block_sender,
            batch_sender=self.block_sender,
            chain_head=chain_head.block,
            identity_signer=self.identity_signer,
            data_dir=None,
            config_dir=None,
            permission_verifier=MockPermissionVerifier(),
            batch_observers=[])
开发者ID:cianx,项目名称:sawtooth-core,代码行数:48,代码来源:block_tree_manager.py


示例16: do_generate

def do_generate(args):
    context = create_context('secp256k1')
    signer = CryptoFactory(context).new_signer(
        context.new_random_private_key())

    words = generate_word_list(args.pool_size)

    batches = []
    start = time.time()
    total_txn_count = 0
    for i in range(0, args.count):
        txns = []
        for _ in range(0, random.randint(1, args.batch_max_size)):
            txn = create_intkey_transaction(
                verb=random.choice(['inc', 'dec']),
                name=random.choice(words),
                value=1,
                signer=signer)
            total_txn_count += 1
            txns.append(txn)

        batch = create_batch(
            transactions=txns,
            signer=signer)

        batches.append(batch)

        if i % 100 == 0 and i != 0:
            stop = time.time()

            txn_count = 0
            for batch in batches[-100:]:
                txn_count += len(batch.transactions)

            fmt = 'batches {}, batch/sec: {:.2f}, txns: {}, txns/sec: {:.2f}'
            print(fmt.format(
                str(i),
                100 / (stop - start),
                str(total_txn_count),
                txn_count / (stop - start)))
            start = stop

    batch_list = batch_pb2.BatchList(batches=batches)

    print("Writing to {}...".format(args.output))
    with open(args.output, "wb") as fd:
        fd.write(batch_list.SerializeToString())
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:47,代码来源:generate.py


示例17: setUp

    def setUp(self):
        self.block_store = BlockStore(DictDatabase(
            indexes=BlockStore.create_index_configuration()))
        self.gossip = MockGossip()
        self.completer = Completer(self.block_store, self.gossip)
        self.completer._on_block_received = self._on_block_received
        self.completer._on_batch_received = self._on_batch_received
        self.completer._has_block = self._has_block
        self._has_block_value = True

        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        crypto_factory = CryptoFactory(context)
        self.signer = crypto_factory.new_signer(private_key)

        self.blocks = []
        self.batches = []
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:17,代码来源:test.py


示例18: __init__

    def __init__(self, with_genesis=True):
        self.block_sender = MockBlockSender()
        self.batch_sender = MockBatchSender()
        self.block_store = BlockStore(DictDatabase(
            indexes=BlockStore.create_index_configuration()))
        self.block_cache = BlockCache(self.block_store)
        self.state_db = {}

        # add the mock reference to the consensus
        consensus_setting_addr = SettingsView.setting_address(
            'sawtooth.consensus.algorithm')
        self.state_db[consensus_setting_addr] = _setting_entry(
            'sawtooth.consensus.algorithm', 'test_journal.mock_consensus')

        self.state_view_factory = MockStateViewFactory(self.state_db)
        context = create_context('secp256k1')
        private_key = context.new_random_private_key()
        crypto_factory = CryptoFactory(context)
        self.signer = crypto_factory.new_signer(private_key)

        identity_private_key = context.new_random_private_key()
        self.identity_signer = crypto_factory.new_signer(identity_private_key)
        chain_head = None
        if with_genesis:
            self.genesis_block = self.generate_genesis_block()
            self.set_chain_head(self.genesis_block)
            chain_head = self.genesis_block

        self.block_publisher = BlockPublisher(
            transaction_executor=MockTransactionExecutor(),
            block_cache=self.block_cache,
            state_view_factory=self.state_view_factory,
            settings_cache=SettingsCache(
                SettingsViewFactory(self.state_view_factory),
            ),
            block_sender=self.block_sender,
            batch_sender=self.block_sender,
            squash_handler=None,
            chain_head=chain_head,
            identity_signer=self.identity_signer,
            data_dir=None,
            config_dir=None,
            permission_verifier=MockPermissionVerifier(),
            check_publish_block_frequency=0.1,
            batch_observers=[])
开发者ID:jjason,项目名称:sawtooth-core,代码行数:45,代码来源:block_tree_manager.py


示例19: is_valid_block

def is_valid_block(block):
    # validate block signature
    header = BlockHeader()
    header.ParseFromString(block.header)

    context = create_context('secp256k1')
    public_key = Secp256k1PublicKey.from_hex(header.signer_public_key)
    if not context.verify(block.header_signature,
                          block.header,
                          public_key):
        LOGGER.debug("block failed signature validation: %s",
                     block.header_signature)
        return False

    # validate all batches in block. These are not all batches in the
    # batch_ids stored in the block header, only those sent with the block.
    if not all(map(is_valid_batch, block.batches)):
        return False

    return True
开发者ID:Whiteblock,项目名称:sawtooth-core,代码行数:20,代码来源:signature_verifier.py


示例20: __init__

    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)
开发者ID:cianx,项目名称:sawtooth-core,代码行数:20,代码来源:intkey_client.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sawtooth_signing.CryptoFactory类代码示例发布时间:2022-05-27
下一篇:
Python rest_client.RestClient类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap