import tempfile
from pathlib import Path
from p2p.identity import PeerIdentity, _b58decode, _b58encode


class TestBase58:
    def test_roundtrip(self):
        data = b"\x00\x01\x02\xff" * 5
        assert _b58decode(_b58encode(data)) == data

    def test_zeros(self):
        assert _b58decode(_b58encode(b"\x00\x00\x00")) == b"\x00\x00\x00"


class TestPeerIdentity:
    def test_generate(self):
        i = PeerIdentity.generate()
        assert i.peer_id.startswith("p2p:")

    def test_deterministic(self):
        i = PeerIdentity.generate()
        assert PeerIdentity(i.private_key).peer_id == i.peer_id

    def test_unique(self):
        assert PeerIdentity.generate().peer_id != PeerIdentity.generate().peer_id

    def test_save_load(self):
        i = PeerIdentity.generate()
        with tempfile.TemporaryDirectory() as t:
            i.save(Path(t) / "k")
            assert PeerIdentity.load(Path(t) / "k").peer_id == i.peer_id

    def test_passphrase(self):
        i = PeerIdentity.generate()
        with tempfile.TemporaryDirectory() as t:
            i.save(Path(t) / "k", "pw")
            assert PeerIdentity.load(Path(t) / "k", "pw").peer_id == i.peer_id

    def test_sign_verify(self):
        i = PeerIdentity.generate()
        assert PeerIdentity.verify(b"hi", i.sign(b"hi"), i.public_key)
        assert not PeerIdentity.verify(b"no", i.sign(b"hi"), i.public_key)

    def test_pem_roundtrip(self):
        i = PeerIdentity.generate()
        pub = PeerIdentity.load_public_key_pem(i.public_key_pem())
        from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
        assert pub.public_bytes(Encoding.Raw, PublicFormat.Raw) == i.public_key_raw()
