Exemplo n.º 1
0
 def test_alpha2(self):
     prefixes = [
         'en', 'aa', 'ab', 'ae', 'af', 'ak', 'am', 'an', 'ar', 'as', 'av',
         'ay', 'az', 'ba', 'be', 'bg', 'bh', 'bi', 'bm', 'bn', 'bo', 'br',
         'bs', 'ca', 'ce', 'ch', 'co', 'cr', 'cs', 'cu', 'cv', 'cy', 'da',
         'de', 'dv', 'dz', 'ee', 'el', 'eo', 'es', 'et', 'eu', 'fa', 'ff',
         'fi', 'fj', 'fo', 'fr', 'fy', 'ga', 'gd', 'gl', 'gn', 'gu', 'gv',
         'ha', 'he', 'hi', 'ho', 'hr', 'ht', 'hu', 'hy', 'hz', 'ia', 'id',
         'ie', 'ig', 'ii', 'ik', 'io', 'is', 'it', 'iu', 'ja', 'jv', 'ka',
         'kg', 'ki', 'kj', 'kk', 'kl', 'km', 'kn', 'ko', 'kr', 'ks', 'ku',
         'kv', 'kw', 'ky', 'la', 'lb', 'lg', 'li', 'ln', 'lo', 'lt', 'lu',
         'lv', 'mg', 'mh', 'mi', 'mk', 'ml', 'mn', 'mr', 'ms', 'mt', 'my',
         'na', 'nb', 'nd', 'ne', 'ng', 'nl', 'nn', 'no', 'nr', 'nv', 'ny',
         'oc', 'oj', 'om', 'or', 'os', 'pa', 'pi', 'pl', 'ps', 'pt', 'qu',
         'rm', 'rn', 'ro', 'ru', 'rw', 'sa', 'sc', 'sd', 'se', 'sg', 'si',
         'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'ss', 'st', 'su', 'sv',
         'sw', 'ta', 'te', 'tg', 'th', 'ti', 'tk', 'tl', 'tn', 'to', 'tr',
         'ts', 'tt', 'tw', 'ty', 'ug', 'uk', 'ur', 'uz', 've', 'vi', 'vo',
         'wa', 'wo', 'xh', 'yi', 'yo', 'za', 'zh', 'zu'
     ]
     for prefix in prefixes:
         metadata = deepcopy(example_010)
         metadata['stream']['metadata']['language'] = prefix
         claim = ClaimDict.load_dict(metadata)
         serialized = claim.serialized
         self.assertDictEqual(
             metadata, dict(ClaimDict.deserialize(serialized).claim_dict))
Exemplo n.º 2
0
def smart_decode(claim_value):
    """
    Decode a claim value

    Try decoding claim protobuf, if this fails try decoding json and migrating it.
    If unable to decode or migrate, raise DecodeError
    """

    # if already decoded, return
    if isinstance(claim_value, ClaimDict):
        return claim_value
    elif isinstance(claim_value, dict):
        return ClaimDict.load_dict(claim_value)

    # see if we were given a hex string, try decoding it
    skip_hex = sum(1 if char not in hex_chars else 0 for char in claim_value)
    if not skip_hex:
        try:
            decoded = claim_value.decode('hex')
            claim_value = decoded
        except (TypeError, ValueError):
            pass

    if claim_value.startswith("{"):
        # try deserializing protobuf, if that fails try parsing from json
        try:
            decoded_json = json.loads(claim_value)
        except (ValueError, TypeError):
            try:
                decoded_claim = ClaimDict.deserialize(claim_value)
                return decoded_claim
            except (DecodeError, InvalidAddress, KeyError):
                raise DecodeError()
        migrated_claim = migrate_json_claim_value(decoded_json)
        return migrated_claim
    else:
        try:
            decoded_claim = ClaimDict.deserialize(claim_value)
            return decoded_claim
        except (DecodeError, InvalidAddress, KeyError):
            try:
                decoded_json = json.loads(claim_value)
            except (ValueError, TypeError):
                raise DecodeError()
            migrated_claim = migrate_json_claim_value(decoded_json)
            return migrated_claim
Exemplo n.º 3
0
 def send_claim_to_address(self,
                           claim_id: str,
                           destination_address: str,
                           amount: Optional[int],
                           account=None):
     account = account or self.default_account
     claims = account.ledger.db.get_utxos(claim_id=claim_id)
     if not claims:
         raise NameError("Claim not found: {}".format(claim_id))
     tx = yield Transaction.update(
         claims[0], ClaimDict.deserialize(claims[0].script.value['claim']),
         amount, destination_address.encode(), [account], account)
     yield self.ledger.broadcast(tx)
     return tx
Exemplo n.º 4
0
def _format_claim_response(outpoint, claim_id, name, amount, height, serialized, channel_id, address, claim_sequence):
    r = {
        "name": name,
        "claim_id": claim_id,
        "address": address,
        "claim_sequence": claim_sequence,
        "value": ClaimDict.deserialize(serialized.decode('hex')).claim_dict,
        "height": height,
        "amount": float(Decimal(amount) / Decimal(COIN)),
        "nout": int(outpoint.split(":")[1]),
        "txid": outpoint.split(":")[0],
        "channel_claim_id": channel_id,
        "channel_name": None
    }
    return r
Exemplo n.º 5
0
 def get_channels(self):
     utxos = yield super().get_unspent_outputs(
         claim_type__any={'is_claim': 1, 'is_update': 1},
         claim_name__like='@%'
     )
     channels = []
     for utxo in utxos:
         d = ClaimDict.deserialize(utxo.script.values['claim'])
         channels.append({
             'name': utxo.claim_name,
             'claim_id': utxo.claim_id,
             'txid': utxo.tx_ref.id,
             'nout': utxo.position,
             'have_certificate': utxo.ref.id in self.certificates
         })
     defer.returnValue(channels)
Exemplo n.º 6
0
    def _save_content_claim(transaction, claim_outpoint, stream_hash):
        # get the claim id and serialized metadata
        claim_info = transaction.execute(
            "select claim_id, serialized_metadata from claim where claim_outpoint=?",
            (claim_outpoint, )).fetchone()
        if not claim_info:
            raise Exception("claim not found")
        new_claim_id, claim = claim_info[0], ClaimDict.deserialize(
            unhexlify(claim_info[1]))

        # certificate claims should not be in the content_claim table
        if not claim.is_stream:
            raise Exception("claim does not contain a stream")

        # get the known sd hash for this stream
        known_sd_hash = transaction.execute(
            "select sd_hash from stream where stream_hash=?",
            (stream_hash, )).fetchone()
        if not known_sd_hash:
            raise Exception("stream not found")
        # check the claim contains the same sd hash
        if known_sd_hash[0].encode() != claim.source_hash:
            raise Exception("stream mismatch")

        # if there is a current claim associated to the file, check that the new claim is an update to it
        current_associated_content = transaction.execute(
            "select claim_outpoint from content_claim where stream_hash=?",
            (stream_hash, )).fetchone()
        if current_associated_content:
            current_associated_claim_id = transaction.execute(
                "select claim_id from claim where claim_outpoint=?",
                current_associated_content).fetchone()[0]
            if current_associated_claim_id != new_claim_id:
                raise Exception(
                    f"mismatching claim ids when updating stream {current_associated_claim_id} vs {new_claim_id}"
                )

        # update the claim associated to the file
        transaction.execute(
            "insert or replace into content_claim values (?, ?)",
            (stream_hash, claim_outpoint))
 def test_stream_is_not_certificate(self):
     deserialized_claim = ClaimDict.deserialize(example_010_serialized.decode('hex'))
     self.assertEquals(deserialized_claim.is_certificate, False)
 def test_deserialize(self):
     deserialized_claim = ClaimDict.deserialize(example_010_serialized.decode('hex'))
     self.assertDictEqual(ClaimDict.load_dict(example_010).claim_dict,
                          deserialized_claim.claim_dict)
Exemplo n.º 9
0
 def claim(self) -> ClaimDict:
     if self.script.is_claim_name or self.script.is_update_claim:
         return ClaimDict.deserialize(self.script.values['claim'])
     raise ValueError(
         'Only claim name and claim update have the claim payload.')
Exemplo n.º 10
0
 def test_stream_is_not_certificate(self):
     deserialized_claim = ClaimDict.deserialize(
         binascii.unhexlify(example_010_serialized))
     self.assertEqual(deserialized_claim.is_certificate, False)
Exemplo n.º 11
0
 def test_deserialize(self):
     deserialized_claim = ClaimDict.deserialize(
         binascii.unhexlify(example_010_serialized))
     self.assertDictEqual(
         ClaimDict.load_dict(example_010).claim_dict,
         deserialized_claim.claim_dict)