예제 #1
0
파일: test_id.py 프로젝트: mateusap1/athena
def test_ids():

    # Verify if the random contract is valid
    assert ID.get_random()["id"].is_valid() == True
    assert ID.is_id_valid(ID.get_random()["id"].to_dict()) == True

    # Verify if the random contract is not valid (when valid == False)
    assert ID.get_random(valid=False)["id"].is_valid() == False
    assert ID.is_id_valid(ID.get_random(valid=False)["id"].to_dict()) == False

    # Should be valid
    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY, NONCE_LIMIT)

    assert ID.is_id_valid(content) == True

    userid = ID(**content)
    assert userid.is_valid() == True

    # Exceeding chars limit
    content = hash_content(
        {
            "username": "******" * (USERNAME_LIMIT + 2),
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY, NONCE_LIMIT)

    assert ID.is_id_valid(content) == False

    userid = ID(**content)
    assert userid.is_valid() == False

    # Tempering the data
    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY, NONCE_LIMIT)

    content["username"] = "******"

    assert ID.is_id_valid(content) == False

    userid = ID(**content)
    assert userid.is_valid() == False

    # Making the hash easier
    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY - 1, NONCE_LIMIT)
    content["hash_value"] = content["hash_value"].replace("0", "a")

    assert ID.is_id_valid(content) == False

    userid = ID(**content)
    assert userid.is_valid() == False
예제 #2
0
파일: Account.py 프로젝트: mateusap1/athena
    def create_id(self):
        """Creates an ID if there isn't one already"""

        try:
            with open(self.info_path) as f:
                self.__info = json.load(f)
        except IOError:
            if self.__username is None:
                raise UnspecifiedInformation("Username not provided")

            content = {
                "username": self.__username,
                "public_key": self.__public_key
            }

            content = hash_content(content, HASH_DIFFICULTY, 10**6)

            info = {
                "id": content,
                "node": self.__node,
                "transactions": self.__transactions
            }

            with open(self.info_path, 'w') as f:
                json.dump(info, f)
예제 #3
0
    def __hash(self) -> None:
        content = {
            "username": self.__username,
            "public_key": self.__public_key
        }

        content = hash_content(content, HASH_DIFFICULTY, 10**6)

        self.__nonce = content["nonce"]
        self.__timestamp = content["timestamp"]
        self.__hash_value = content["hash_value"]
예제 #4
0
    def timestamped_uri_to_version(self,
                                   dt,
                                   uri,
                                   *,
                                   url,
                                   maintainers=None,
                                   tags=None,
                                   view_url=None):
        """
        Fetch version content and combine it with metadata to build a Version.

        Parameters
        ----------
        dt : datetime.datetime
            capture time
        uri : string
            URI of version
        url : string
            page URL
        maintainers : list of string, optional
            Entities responsible for maintaining the page, as a list of strings
        tags : list of string, optional
            Any arbitrary "tags" to apply to the page for categorization
        view_url : string, optional
            The archive.org URL for viewing the page (with rewritten links, etc.)

        Returns
        -------
        dict : Version
            suitable for passing to :class:`Client.add_versions`
        """
        with utils.rate_limited(group='timestamped_uri_to_version'):
            # Check to make sure we are actually getting a memento playback.
            res = utils.retryable_request('GET',
                                          uri,
                                          allow_redirects=False,
                                          session=self.session)
            if res.headers.get('memento-datetime') is None:
                message = res.headers.get('X-Archive-Wayback-Runtime-Error')
                if message:
                    raise MementoPlaybackError(
                        f'Memento at {uri} could not be played: {message}')
                elif res.ok:
                    raise MementoPlaybackError(
                        f'Memento at {uri} could not be played')
                else:
                    res.raise_for_status()

            # If the playback includes a redirect, continue on.
            if res.status_code >= 300 and res.status_code < 400:
                original = res
                res = utils.retryable_request('GET',
                                              res.headers.get('location'),
                                              session=self.session)
                res.history.insert(0, original)
                res.request = original.request

        version_hash = utils.hash_content(res.content)
        title = utils.extract_title(res.content)
        content_type = (res.headers['content-type'] or '').split(';', 1)

        # Get all headers from original response
        prefix = 'X-Archive-Orig-'
        original_headers = {
            k[len(prefix):]: v
            for k, v in res.headers.items() if k.startswith(prefix)
        }

        redirected_url = None
        redirects = None
        if res.url != uri:
            redirected_url = original_url_for_memento(res.url)
            redirects = list(
                map(lambda response: original_url_for_memento(response.url),
                    res.history))
            redirects.append(redirected_url)

        return format_version(url=url,
                              dt=dt,
                              uri=uri,
                              version_hash=version_hash,
                              title=title,
                              tags=tags,
                              maintainers=maintainers,
                              status=res.status_code,
                              mime_type=content_type[0],
                              encoding=res.encoding,
                              headers=original_headers,
                              view_url=view_url,
                              redirected_url=redirected_url,
                              redirects=redirects)
예제 #5
0
def test_contract():

    # Valid random contract
    c = Contract.get_random()["contract"]
    assert c.is_valid() == True

    # Invalid random contract
    c = Contract.get_random(valid=False)["contract"]
    assert c.is_valid() == False

    judges = [ID("Agatha Christie", parsed_pubkey) for _ in range(MIN_JUDGES)]
    rule = {
        "content": "You shall not kill",
        "sentence": "Some really bad thing",
        "reward": {
            "value": 1000,
            "currency": "Nano"
        }
    }
    rules = [rule for _ in range(MIN_RULES)]
    expire = datetime.datetime.now() + datetime.timedelta(days=1)

    # Should be valid as well
    c = Contract(userid, rules, judges, expire)
    c.sign(key)
    assert c.is_valid() == True

    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY - 1, NONCE_LIMIT)

    content["hash_value"] = content["hash_value"].replace("0", "a")
    invalid_id = ID(**content)

    # Invalid ID
    c = Contract(invalid_id, rules, judges, expire)
    c.sign(key)
    assert c.is_valid() == False

    # Unmatching key
    c = Contract(userid, rules, judges, expire)
    c.sign(create_key())
    assert c.is_valid() == False

    # No judges
    c = Contract(userid, rules, [], expire)
    c.sign(key)
    assert c.is_valid() == False

    # No rules
    c = Contract(userid, [], judges, expire)
    c.sign(key)
    assert c.is_valid() == False

    # Sender as judge
    c = Contract(userid, rules, [userid], expire)
    c.sign(key)
    assert c.is_valid() == SENDER_CAN_JUDGE

    # Repeated judges
    c = Contract(userid, rules, [judges[0] for _ in range(MAX_JUDGES)], expire)
    c.sign(key)
    assert c.is_valid() == False

    expired = datetime.datetime.now() - datetime.timedelta(days=1)
    c = Contract(userid, rules, judges, expired)
    c.sign(key)
    assert c.is_valid() == False
예제 #6
0
def test_appeal():

    # Valid random appeal
    a = Appeal.get_random()["appeal"]
    assert a.is_valid() == True

    # Invalid random appeal
    a = Appeal.get_random(valid=False)["appeal"]
    assert a.is_valid() == False

    judges = [ID.get_random()["id"] for _ in range(MIN_JUDGES)]
    rule = {
        "content": "You shall not kill",
        "sentence": "Some really bad thing",
        "reward": {
            "value": 1000,
            "currency": "Nano"
        }
    }
    rules = [rule for _ in range(MIN_RULES)]
    expire = datetime.datetime.now() + datetime.timedelta(days=1)

    contract = Contract(userid, rules, judges, expire)
    contract.sign(key)

    accused = ID("Hercule Poirot", parsed_pubkey)
    accusation = Accusation(userid, accused, contract)
    accusation.sign(key)

    sentence = "Must be executed"
    description = "Because I say so"

    verdict = Verdict(userid, accusation, sentence, description)
    verdict.sign(key)

    # Valid hardcoded appeal
    a = Appeal(userid, verdict)
    a.sign(key)
    assert a.is_valid() == True

    with pytest.raises(TypeError):
        a = Appeal("User", verdict)
    with pytest.raises(TypeError):
        a = Appeal(userid, {"content": "..."})

    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY - 1, NONCE_LIMIT)

    content["hash_value"] = content["hash_value"].replace("0", "a")
    invalid_id = ID(**content)

    # Invalid sender's ID
    a = Appeal(invalid_id, verdict)
    a.sign(key)
    assert a.is_valid() == False

    # Unmatching key
    a = Appeal(userid, verdict)
    a.sign(create_key())
    assert a.is_valid() == False

    invalid_verdict = Verdict(userid, accusation, "", description)
    invalid_verdict.sign(key)

    # Invalid verdict
    a = Appeal(userid, invalid_verdict)
    a.sign(key)
    assert a.is_valid() == False
예제 #7
0
def test_verdict():

    # Valid random verdict
    v = Verdict.get_random()["verdict"]
    assert v.is_valid() == True

    # Invalid random verdict
    v = Verdict.get_random(valid=False)["verdict"]
    assert v.is_valid() == False

    judges = [ID.get_random()["id"] for _ in range(MIN_JUDGES)]
    rule = {
        "content": "You shall not kill",
        "sentence": "Some really bad thing",
        "reward": {
            "value": 1000,
            "currency": "Nano"
        }
    }
    rules = [rule for _ in range(MIN_RULES)]
    expire = datetime.datetime.now() + datetime.timedelta(days=1)
    contract = Contract(userid, rules, judges, expire)
    contract.sign(key)
    accused = ID("Hercule Poirot", parsed_pubkey)

    accusation = Accusation(userid, accused, contract)
    accusation.sign(key)
    sentence = "Must be executed"
    description = "Because I say so"

    # Should be valid as well
    v = Verdict(userid, accusation, sentence, description)
    v.sign(key)
    assert v.is_valid() == True

    with pytest.raises(TypeError):
        v = Verdict("User", accusation, sentence, description)
    with pytest.raises(TypeError):
        v = Verdict(userid, {"content": "..."}, sentence, description)
    with pytest.raises(TypeError):
        v = Verdict(userid, accusation, False, description)
    with pytest.raises(TypeError):
        v = Verdict(userid, accusation, sentence, 76)

    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY - 1, NONCE_LIMIT)

    content["hash_value"] = content["hash_value"].replace("0", "a")
    invalid_id = ID(**content)

    # Invalid sender's ID
    v = Verdict(invalid_id, accusation, sentence, description)
    v.sign(key)
    assert v.is_valid() == False

    # Unmatching key
    v = Verdict(userid, accusation, sentence, description)
    v.sign(create_key())
    assert v.is_valid() == False

    # Invalid accusation
    v = Verdict(userid,
                Accusation.get_random(valid=False)["accusation"], sentence,
                description)
    v.sign(key)
    assert v.is_valid() == False

    # No sentence at all
    v = Verdict(userid, accusation, "", description)
    v.sign(key)
    assert v.is_valid() == False

    # Sentence with more chars than the allowed
    v = Verdict(userid, accusation, "c" * (SENTECE_CHAR_LIMIT + 1),
                description)
    v.sign(key)
    assert v.is_valid() == False

    # Description with more chars than the allowed
    v = Verdict(userid, accusation, sentence,
                "c" * (DESCRIPTION_CHAR_LIMIT + 1))
    v.sign(key)
    assert v.is_valid() == False
예제 #8
0
def test_accusation():

    # Valid random accusation
    a = Accusation.get_random()["accusation"]
    assert a.is_valid() == True

    # Invalid random accusation
    a = Accusation.get_random(valid=False)["accusation"]
    assert a.is_valid() == False

    judges = [ID.get_random()["id"] for _ in range(MIN_JUDGES)]
    rule = {
        "content": "You shall not kill",
        "sentence": "Some really bad thing",
        "reward": {
            "value": 1000,
            "currency": "Nano"
        }
    }
    rules = [rule for _ in range(MIN_RULES)]
    expire = datetime.datetime.now() + datetime.timedelta(days=1)

    contract = Contract(userid, rules, judges, expire)
    contract.sign(key)
    accused = ID("Murray Rothbard", parsed_pubkey)

    # Should be valid as well
    a = Accusation(userid, accused, contract)
    a.sign(key)
    assert a.is_valid() == True

    with pytest.raises(TypeError):
        a = Accusation("User", accused, contract)
    with pytest.raises(TypeError):
        a = Accusation(userid, "Accused", contract)
    with pytest.raises(TypeError):
        a = Accusation(userid, accused, {"content": "..."})

    content = hash_content(
        {
            "username": "******",
            "public_key": parsed_pubkey
        }, HASH_DIFFICULTY - 1, NONCE_LIMIT)

    content["hash_value"] = content["hash_value"].replace("0", "a")
    invalid_id = ID(**content)

    # Invalid sender's ID
    a = Accusation(invalid_id, accused, contract)
    a.sign(key)
    assert a.is_valid() == False

    # Invalid accused's ID
    a = Accusation(userid, invalid_id, contract)
    a.sign(key)
    assert a.is_valid() == False

    # Unmatching key
    a = Accusation(userid, accused, contract)
    a.sign(create_key())
    assert a.is_valid() == False

    # Invalid contract
    a = Accusation(userid, accused,
                   Contract.get_random(valid=False)["contract"])
    a.sign(key)
    assert a.is_valid() == False