Пример #1
0
 def test_signer_from_pubkey(self):
     self.assertRaises(TypeError,
                       lambda: Signer.from_pubkey(self.public_key_bytes))
     self.assertRaises(
         TypeError, lambda: Signer.from_pubkey_file(self.public_der_path))
     self.assertRaises(
         TypeError, lambda: Signer.from_pubkey_file(self.public_pem_path))
Пример #2
0
 async def __init_peer_auth(self):
     try:
         node_key: bytes = await StubCollection().peer_stub.async_task().get_node_key(ChannelProperty().name)
         self.__peer_auth = Signer.from_prikey(node_key)
     except KeyError:
         self.__peer_auth = Signer.from_channel(ChannelProperty().name)
     except Exception as e:
         logging.exception(f"peer auth init fail cause : {e}")
         util.exit_and_msg(f"peer auth init fail cause : {e}")
Пример #3
0
 async def __init_peer_auth(self):
     try:
         node_key: bytes = await StubCollection().peer_stub.async_task().get_node_key()
         self.__peer_auth = Signer.from_prikey(node_key)
         ChannelProperty().peer_auth = self.__peer_auth
     except Exception as e:
         utils.exit_and_msg(f"peer auth init fail cause : {e}")
Пример #4
0
    def test_valid_timestamp(self):
        """Test for timestamp buffer in block verifier"""
        def block_maker(timestamp: int, height: int = 0, prev_hash=None):
            """Make dummy block"""
            tx_versioner = TransactionVersioner()

            dummy_receipts = {}
            block_builder = BlockBuilder.new("0.1a", tx_versioner)

            for i in range(1000):
                tx_builder = TransactionBuilder.new("0x3", None, tx_versioner)
                tx_builder.signer = test_signer
                tx_builder.to_address = ExternalAddress.new()
                tx_builder.step_limit = random.randint(0, 10000)
                tx_builder.value = random.randint(0, 10000)
                tx_builder.nid = 2
                tx = tx_builder.build()

                tx_serializer = TransactionSerializer.new(tx.version, tx.type(), tx_versioner)
                block_builder.transactions[tx.hash] = tx
                dummy_receipts[tx.hash.hex()] = {
                    "dummy_receipt": "dummy",
                    "tx_dumped": tx_serializer.to_full_data(tx)
                }

            block_builder.signer = test_signer
            block_builder.prev_hash = prev_hash
            block_builder.height = height
            block_builder.state_hash = Hash32(bytes(Hash32.size))
            block_builder.receipts = dummy_receipts
            block_builder.reps = [ExternalAddress.fromhex_address(test_signer.address)]
            block_builder.peer_id = ExternalAddress.fromhex(test_signer.address)
            block_builder.next_leader = ExternalAddress.fromhex(test_signer.address)
            block_builder.fixed_timestamp = timestamp

            b = block_builder.build()
            assert b.header.timestamp == timestamp

            return b

        test_signer = Signer.from_prikey(os.urandom(32))

        first_block = block_maker(height=0, timestamp=utils.get_time_stamp())
        second_block = block_maker(height=1, timestamp=utils.get_time_stamp() + 5, prev_hash=first_block.header.hash)
        third_block_from_far_future = block_maker(height=2, prev_hash=second_block.header.hash,
                                                  timestamp=utils.get_time_stamp() + conf.TIMESTAMP_BUFFER_IN_VERIFIER + 5_000_000)

        block_verifier = BlockVerifier.new("0.1a", TransactionVersioner())
        leader = first_block.header.peer_id
        reps = [ExternalAddress.fromhex_address(test_signer.address)]
        print("*---Normal time range")
        block_verifier.verify(block=second_block, prev_block=first_block,
                              blockchain=None, generator=leader, reps=reps)

        print("*---Abnormal time range")
        with self.assertRaises(Exception):
            block_verifier.verify(block=third_block_from_far_future, prev_block=second_block,
                                  blockchain=None, generator=leader, reps=reps)
Пример #5
0
def set_mock(test):
    peer_auth = Signer.from_prikey(os.urandom(32))
    test.peer_auth = peer_auth
    peer_service_mock = PeerServiceMock()
    peer_service_mock.peer_manager = PeerManagerMock(peer_auth)
    peer_service_mock.channel_service = ChannelServiceMock(conf.LOOPCHAIN_DEFAULT_CHANNEL)

    ObjectManager().peer_service = peer_service_mock
    ObjectManager().channel_service = peer_service_mock.channel_service
Пример #6
0
    def setUp(self):
        test_util.print_testname(self._testMethodName)
        self.peer_auth = Signer.from_prikey(os.urandom(32))

        set_mock(self)
        # BlockChain 을 만듬
        test_db = test_util.make_level_db(self.db_name)
        self.assertIsNotNone(test_db, "DB생성 불가")
        self.chain = BlockChain(test_db)
Пример #7
0
    def setUp(self):
        test_util.print_testname(self._testMethodName)
        self.peer_auth = Signer.from_prikey(os.urandom(32))

        set_mock(self)
        # BlockChain 을 만듬
        self.test_store = test_util.make_key_value_store('blockchain_db')
        self.assertIsNotNone(self.test_store, "DB생성 불가")
        self.chain = BlockChain(self.test_store)
Пример #8
0
    def _init_node_key(self):
        prikey_file = conf.PRIVATE_PATH

        if conf.PRIVATE_PASSWORD:
            password = conf.PRIVATE_PASSWORD
        else:
            password = getpass.getpass(f"Input your keystore password: ")
        signer = Signer.from_prikey_file(prikey_file, password)
        self._make_peer_id(signer.address)
        self._node_key = signer.get_private_secret()
Пример #9
0
 def _tx_item(tx_versioner: TransactionVersioner) -> Transaction:
     test_signer = Signer.from_prikey(os.urandom(32))
     tx_builder = TransactionBuilder.new("0x3", "", tx_versioner)
     tx_builder.signer = test_signer
     tx_builder.to_address = ExternalAddress.new()
     tx_builder.step_limit = random.randint(0, 10000)
     tx_builder.value = random.randint(0, 10000)
     tx_builder.nid = 2
     tx: Transaction = tx_builder.build()
     return tx
Пример #10
0
    def __make_peer_id(self):
        """네트워크에서 Peer 를 식별하기 위한 UUID를 level db 에 생성한다.
        """
        self.__peer_id = Signer.from_channel(
            conf.LOOPCHAIN_DEFAULT_CHANNEL).address

        logger_preset = loggers.get_preset()
        logger_preset.peer_id = self.peer_id
        logger_preset.update_logger()

        logging.info(f"run peer_id : {self.__peer_id}")
Пример #11
0
    def test_sign_transaction_raises_exc_if_signer_addr_ne_tx_signer_addr(
            self, tx_builder_factory: TxBuilderFactory, tx_version):
        tx_builder = tx_builder_factory(tx_version)
        tx = tx_builder.build()

        tx_builder.signer = Signer.new()

        if tx_version == genesis.version:
            with pytest.raises(NotImplementedError):
                tx_builder.sign_transaction(tx)
        else:
            with pytest.raises(RuntimeError, match="Signer not match"):
                tx_builder.sign_transaction(tx)
Пример #12
0
    def _tx_builder_factory(tx_version: str, type_=None) -> TransactionBuilder:
        tx_builder = TransactionBuilder.new(version=tx_version, type_=type_, versioner=TransactionVersioner())

        # Attributes that must be assigned
        tx_builder.signer = Signer.new()

        if tx_version == genesis.version:
            tx_builder = add_attrs_to_genesis_builder(tx_builder)
        elif tx_version == v2.version:
            tx_builder = add_attrs_to_v2_builder(tx_builder)
        elif tx_version == v3.version:
            tx_builder = add_attrs_to_v3_builder(tx_builder)

        return tx_builder
Пример #13
0
    def test_transaction_v2_unsigned(self):
        signer = Signer.new()

        tb = TransactionBuilder.new("0x2", None, self.tx_versioner)
        tb.fee = 1000000
        tb.value = 100000
        tb.from_address = ExternalAddress.fromhex_address(signer.address)
        tb.to_address = ExternalAddress(os.urandom(20))
        tb.nonce = random.randint(0, 100000)
        tx = tb.build(is_signing=False)

        tv = TransactionVerifier.new("0x2", tx.type(), self.tx_versioner)
        self.assertRaises(TransactionInvalidSignatureError, lambda: tv.verify(tx))
        self.assertRaises(TransactionInvalidSignatureError, lambda: tv.pre_verify(tx))

        tb.signer = signer
        signed_tx = tb.sign_transaction(tx)
        tv.verify(signed_tx)
        tv.pre_verify(signed_tx)
Пример #14
0
def key_convert():
    import os

    if os.path.exists(conf.PRIVATE_PATH) and conf.PRIVATE_PATH.endswith(
        (".pem", ".der")):
        import getpass
        import re
        from loopchain.crypto.signature import Signer
        from eth_keyfile import create_keyfile_json

        private_path = conf.PRIVATE_PATH
        password = conf.PRIVATE_PASSWORD
        if not password:
            password = getpass.getpass(f"Input your keystore password: "******"Something wrong. {e!r}")
            return

        private_key = signer.private_key.secret
        address = signer.address

        key_store_contents = create_keyfile_json(private_key,
                                                 bytes(password, "utf-8"),
                                                 iterations=16384,
                                                 kdf="scrypt")
        key_store_contents["address"] = address
        key_store_contents["coinType"] = "icx"

        new_keypath = re.sub("(pem|der)$", "json", private_path)
        with open(new_keypath, 'w') as f:
            f.write(json.dumps(key_store_contents))

        print(
            f"{new_keypath} created. update your PRIVATE_PATH in config file")
    else:
        print(f"Nothing to do. you don't have .pem or .der key file!")
Пример #15
0
    def test_transaction_v3_unsigned(self):
        signer = Signer.new()

        tb = TransactionBuilder.new("0x3", None, self.tx_versioner)
        tb.step_limit = 1000000
        tb.value = 100000
        tb.from_address = ExternalAddress.fromhex_address(signer.address)
        tb.to_address = ExternalAddress(os.urandom(20))
        tb.nid = 3
        tb.nonce = random.randint(0, 100000)
        tb.data = "test"
        tb.data_type = "message"
        tx = tb.build(False)

        tv = TransactionVerifier.new("0x3", tx.type(), self.tx_versioner)
        self.assertRaises(TransactionInvalidSignatureError, lambda: tv.verify(tx))
        self.assertRaises(TransactionInvalidSignatureError, lambda: tv.pre_verify(tx, nid=3))

        tb.signer = signer
        signed_tx = tb.sign_transaction(tx)
        tv.verify(signed_tx)
        tv.pre_verify(signed_tx, nid=3)
Пример #16
0
    def setUp(self):
        self.channel_name = conf.LOOPCHAIN_DEFAULT_CHANNEL
        test_util.print_testname(self._testMethodName)
        self.peer_auth = Signer.from_prikey(os.urandom(32))

        set_mock(self)
Пример #17
0
def pytest_configure():
    signers = [Signer.from_prikey(os.urandom(32)) for _ in range(100)]
    reps = [ExternalAddress.fromhex_address(signer.address) for signer in signers]

    pytest.SIGNERS: List[Signer] = signers
    pytest.REPS: List[ExternalAddress] = reps
Пример #18
0
 def setUp(self):
     conf.Configure().init_configure()
     test_util.print_testname(self._testMethodName)
     self.peer_auth = Signer.from_prikey(os.urandom(32))
     set_mock(self)
Пример #19
0
    def test_block_v0_4(self):
        block_version = "0.4"
        test_signer = Signer.from_prikey(os.urandom(32))
        tx_versioner = TransactionVersioner()

        dummy_receipts = {}
        block_builder = BlockBuilder.new(block_version, tx_versioner)
        for i in range(5):
            tx_builder = TransactionBuilder.new("0x3", None, tx_versioner)
            tx_builder.signer = test_signer
            tx_builder.to_address = ExternalAddress.new()
            tx_builder.step_limit = random.randint(0, 10000)
            tx_builder.value = random.randint(0, 10000)
            tx_builder.nid = 2
            tx = tx_builder.build()

            tx_serializer = TransactionSerializer.new(tx.version, tx.type(),
                                                      tx_versioner)
            block_builder.transactions[tx.hash] = tx
            dummy_receipts[tx.hash.hex()] = {
                "dummy_receipt": "dummy",
                "tx_dumped": tx_serializer.to_full_data(tx)
            }

        next_leader = ExternalAddress.fromhex(
            "hx00112233445566778899aabbccddeeff00112233")

        block_builder.signer = test_signer
        block_builder.height = 0
        block_builder.prev_hash = Hash32(bytes(Hash32.size))
        block_builder.state_hash = Hash32(bytes(Hash32.size))
        block_builder.receipts = dummy_receipts
        block_builder.reps = [
            ExternalAddress.fromhex_address(test_signer.address)
        ]
        block_builder.next_leader = next_leader
        block_builder.next_reps = []

        vote = BlockVote.new(test_signer, utils.get_time_stamp(),
                             block_builder.height - 1, 0,
                             block_builder.prev_hash)
        votes = BlockVotes(block_builder.reps, conf.VOTING_RATIO,
                           block_builder.height - 1, 0,
                           block_builder.prev_hash)
        votes.add_vote(vote)
        block_builder.prev_votes = votes.votes

        block = block_builder.build()
        block_verifier = BlockVerifier.new(block_version, tx_versioner)

        block_verifier.invoke_func = lambda b, prev_b: (block, dummy_receipts)
        reps_getter = lambda _: block_builder.reps
        generator = ExternalAddress.fromhex_address(test_signer.address)
        block_verifier.verify(block,
                              None,
                              None,
                              generator=generator,
                              reps_getter=reps_getter)

        block_serializer = BlockSerializer.new(block_version, tx_versioner)
        block_serialized = block_serializer.serialize(block)
        logging.info(json.dumps(block_serialized, indent=4))
        block_deserialized = block_serializer.deserialize(block_serialized)
        logging.info(
            json.dumps(block_serializer.serialize(block_deserialized),
                       indent=4))

        assert block.header == block_deserialized.header
        assert block.body == block_deserialized.body

        tx_hashes = list(block.body.transactions)
        tx_index = random.randrange(0, len(tx_hashes))

        block_prover = BlockProver.new(block.header.version, tx_hashes,
                                       BlockProverType.Transaction)
        tx_proof = block_prover.get_proof(tx_index)
        assert block_prover.prove(tx_hashes[tx_index],
                                  block.header.transactions_hash, tx_proof)

        block_prover = BlockProver.new(block.header.version,
                                       block_builder.receipts,
                                       BlockProverType.Receipt)
        receipt_proof = block_prover.get_proof(tx_index)
        receipts_hash = block_prover.to_hash32(
            block_builder.receipts[tx_index])
        assert block_prover.prove(receipts_hash, block.header.receipts_hash,
                                  receipt_proof)
Пример #20
0
 def setUpClass(cls):
     cls.signers = [Signer.from_prikey(os.urandom(32)) for _ in range(100)]
     cls.reps = [
         ExternalAddress.fromhex_address(signer.address)
         for signer in cls.signers
     ]
Пример #21
0
    def new(cls, signer: Signer, timestamp: int, **kwargs):
        rep_id: ExternalAddress = ExternalAddress.fromhex(signer.address)

        hash_ = cls.to_hash(rep_id, timestamp, **kwargs)
        signature = Signature(signer.sign_hash(hash_))
        return cls(rep_id, timestamp, signature, **kwargs)
Пример #22
0
 def setUp(self):
     test_util.print_testname(self._testMethodName)
     self.signer = Signer.from_prikey(os.urandom(32))
     self.tx_versioner = TransactionVersioner()
     self.tx_versioner.hash_generator_versions["0x2"] = 0
Пример #23
0
    def setUpClass(cls) -> None:
        cls.temp_dir = tempfile.TemporaryDirectory()

        # Private Key
        cls.private_key = ec.generate_private_key(ec.SECP256K1, default_backend())

        cls.private_der_path = os.path.join(cls.temp_dir.name, "private.der")
        with open(cls.private_der_path, "wb") as private_der_file:
            private_der_file.write(
                cls.private_key.private_bytes(
                    encoding=serialization.Encoding.DER,
                    format=serialization.PrivateFormat.PKCS8,
                    encryption_algorithm=serialization.BestAvailableEncryption(b"TEST")
                )
            )

        cls.private_pem_path = os.path.join(cls.temp_dir.name, "private.pem")
        with open(cls.private_pem_path, "wb") as private_pem_file:
            private_pem_file.write(
                cls.private_key.private_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PrivateFormat.PKCS8,
                    encryption_algorithm=serialization.BestAvailableEncryption(b"TEST")
                )
            )

        key_info = keys.PrivateKeyInfo.load(cls.private_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ))
        cls.private_key_bytes = long_to_bytes(key_info['private_key'].native['private_key'])

        # Public Key
        cls.public_key = cls.private_key.public_key()

        cls.public_der_path = os.path.join(cls.temp_dir.name, "public.der")
        with open(cls.public_der_path, "wb") as public_der_file:
            public_der_file.write(
                cls.public_key.public_bytes(
                    encoding=serialization.Encoding.DER,
                    format=serialization.PublicFormat.SubjectPublicKeyInfo
                )
            )

        cls.public_pem_path = os.path.join(cls.temp_dir.name, "public.pem")
        with open(cls.public_pem_path, "wb") as public_pem_file:
            public_pem_file.write(
                cls.public_key.public_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PublicFormat.SubjectPublicKeyInfo
                )
            )

        key_info = keys.PublicKeyInfo.load(
            cls.public_key.public_bytes(
                encoding=serialization.Encoding.DER,
                format=serialization.PublicFormat.SubjectPublicKeyInfo
            )
        )
        cls.public_key_bytes = key_info['public_key'].native

        cls.signer_private_key_bytes = Signer.from_prikey(cls.private_key_bytes)
        cls.signer_private_key_der = Signer.from_prikey_file(cls.private_der_path, b"TEST")
        cls.signer_private_key_pem = Signer.from_prikey_file(cls.private_pem_path, b"TEST")

        cls.sign_verifier_private_key_bytes = SignVerifier.from_prikey(cls.private_key_bytes)
        cls.sign_verifier_private_key_der = SignVerifier.from_prikey_file(cls.private_der_path, b"TEST")
        cls.sign_verifier_private_key_pem = SignVerifier.from_prikey_file(cls.private_pem_path, b"TEST")

        cls.sign_verifier_public_key_bytes = SignVerifier.from_pubkey(cls.public_key_bytes)
        cls.sign_verifier_public_key_der = SignVerifier.from_pubkey_file(cls.public_der_path)
        cls.sign_verifier_public_key_pem = SignVerifier.from_pubkey_file(cls.public_pem_path)
    def setUp(self):
        test_util.print_testname(self._testMethodName)
        self.peer_auth = Signer.from_prikey(os.urandom(32))

        set_mock(self)
Пример #25
0
    @pytest.mark.parametrize("rest_method", RestMethod)
    def test_url(self, rest_client: RestClient, rest_method: RestMethod):
        url = rest_client.create_url(rest_client._target, rest_method)
        assert url == request_urls[rest_method]

    @pytest.mark.parametrize("rest_method", RestMethod)
    def test_params(self, rest_client: RestClient, rest_method: RestMethod):
        params = rest_client.create_params(rest_method,
                                           request_params[rest_method])
        params.pop('id', None)
        assert params == request_params_results[rest_method]


tv = TransactionVersioner()
tb = TransactionBuilder.new(version="0x2", type_=None, versioner=tv)
tb.signer = Signer.new()
tb.to_address = ExternalAddress(os.urandom(20))
tb.fee = 10
tb.value = 1000
tb.nonce = 123
request_tx2 = tb.build()
request_tx2_param = TransactionSerializer.new("0x2", None,
                                              tv).to_raw_data(request_tx2)
request_tx2_param["from_"] = request_tx2_param.pop("from")

tb = TransactionBuilder.new(version="0x3", type_=None, versioner=tv)
tb.step_limit = 1000000
tb.value = 100000
tb.signer = Signer.new()
tb.to_address = ExternalAddress(os.urandom(20))
tb.nid = 3
Пример #26
0
 def __init_key_by_channel(self):
     for channel in conf.CHANNEL_OPTION:
         signer = Signer.from_channel(channel)
         if channel == conf.LOOPCHAIN_DEFAULT_CHANNEL:
             self.__make_peer_id(signer.address)
         self.__node_keys[channel] = signer.private_key.private_key
Пример #27
0
 def __init_peer_auth(self):
     try:
         self.__peer_auth = Signer.from_channel(ChannelProperty().name)
     except Exception as e:
         logging.exception(f"peer auth init fail cause : {e}")
         util.exit_and_msg(f"peer auth init fail cause : {e}")