Ejemplo n.º 1
0
Archivo: emi.py Proyecto: SLeeTech/EMI
    def create_next_address(address):
        # create next address from root_address
        astrits = TryteString(str(root_address).encode()).as_trits()
        checksum_trits = []
        sponge = Kerl()
        sponge.absorb(astrits)
        sponge.squeeze(checksum_trits)
        result = TryteString.from_trits(checksum_trits)
        next_address = Address(result)

        # check if the next address is unsused
        check_address = api.find_transactions(addresses=[next_address])
        if len(check_address['hashes']) == 0:
            address_empty = True
        else:
            address_empty = False

        # If new address is used create find an empty address
        if address_empty == False:
            astrits = TryteString(
                (str(next_address) + str(root_address)).encode()).as_trits()
            checksum_trits = []
            sponge = Kerl()
            sponge.absorb(astrits)
            sponge.squeeze(checksum_trits)
            result = TryteString.from_trits(checksum_trits)
            next_address = Address(result)
        else:
            next_address = next_address

        return next_address
Ejemplo n.º 2
0
  def __next__(self):
    # type: () -> TryteString
    """
    Returns the next signature fragment.
    """
    key_trytes = next(self._key_chunks) # type: TryteString
    self._iteration += 1

    # If the key is long enough, loop back around to the start.
    normalized_chunk =\
      self._normalized_hash[self._iteration % len(self._normalized_hash)]

    signature_fragment = key_trytes.as_trits()

    # Build the signature, one hash at a time.
    for i in range(key_trytes.count_chunks(Hash.LEN)):
      hash_start  = i * HASH_LENGTH
      hash_end    = hash_start + HASH_LENGTH

      buffer = signature_fragment[hash_start:hash_end] # type: MutableSequence[int]

      for _ in range(13 - normalized_chunk[i]):
        self._sponge.reset()
        self._sponge.absorb(buffer)
        self._sponge.squeeze(buffer)

      signature_fragment[hash_start:hash_end] = buffer

    return TryteString.from_trits(signature_fragment)
Ejemplo n.º 3
0
 def value_as_trytes(self):
     # type: () -> TryteString
     """
 Returns a TryteString representation of the transaction's value.
 """
     # Note that we are padding to 81 _trits_.
     return TryteString.from_trits(trits_from_int(self.value, pad=81))
Ejemplo n.º 4
0
  def test_length_greater_than_243(self):
    """
    The input is longer than 1 hash.
    """
    # noinspection SpellCheckingInspection
    input_ = (
      'G9JYBOMPUXHYHKSNRNMMSSZCSHOFYOYNZRSZMAAYWDYEIMVVOGKPJB'
      'VBM9TDPULSFUNMTVXRKFIDOHUXXVYDLFSZYZTWQYTE9SPYYWYTXJYQ'
      '9IFGYOLZXWZBKWZN9QOOTBQMWMUBLEWUEEASRHRTNIQWJQNDWRYLCA'
    )

    trits = TryteString(input_).as_trits()

    curl = Curl()
    curl.absorb(trits)
    trits_out = []
    curl.squeeze(trits_out)

    trits_out = TryteString.from_trits(trits_out)

    # noinspection SpellCheckingInspection
    self.assertEqual(
      trits_out,

      'RWCBOLRFANOAYQWXXTFQJYQFAUTEEBSZWTIRSSDR'
      'EYGCNFRLHQVDZXYXSJKCQFQLJMMRHYAZKRRLQZDKR',
    )
Ejemplo n.º 5
0
  def test_happy_path(self):
    """
    Typical use case.
    """
    # noinspection SpellCheckingInspection
    input_ = (
      'EMIDYNHBWMBCXVDEFOFWINXTERALUKYYPPHKP9JJ'
      'FGJEIUY9MUDVNFZHMMWZUYUSWAIOWEVTHNWMHANBH'
    )

    trits = TryteString(input_).as_trits()
    

    curl = Curl()
    curl.absorb(trits)
    trits_out = []
    curl.squeeze(trits_out)

    trits_out = TryteString.from_trits(trits_out)
    # print('trits_out: ', trits_out)
    # # AQBOPUMJMGVHFOXSMUAGZNACKUTISDPBSILMRAGIGRXXS9JJTLIKZUW9BCJWKSTFBDSBLNVEEGVGAMSSM

    # noinspection SpellCheckingInspection
    self.assertEqual(
      trits_out,

      'AQBOPUMJMGVHFOXSMUAGZNACKUTISDPBSILMRAGI'
      'GRXXS9JJTLIKZUW9BCJWKSTFBDSBLNVEEGVGAMSSM',
    )
Ejemplo n.º 6
0
  def __next__(self):
    # type: () -> TryteString
    """
    Returns the next signature fragment.
    """
    key_trytes = next(self._key_chunks) # type: TryteString
    self._iteration += 1

    # If the key is long enough, loop back around to the start.
    normalized_chunk =\
      self._normalized_hash[self._iteration % len(self._normalized_hash)]

    signature_fragment = key_trytes.as_trits()

    # Build the signature, one hash at a time.
    for i in range(key_trytes.count_chunks(Hash.LEN)):
      hash_start  = i * HASH_LENGTH
      hash_end    = hash_start + HASH_LENGTH

      buffer = signature_fragment[hash_start:hash_end] # type: MutableSequence[int]

      for _ in range(13 - normalized_chunk[i]):
        self._sponge.reset()
        self._sponge.absorb(buffer)
        self._sponge.squeeze(buffer)

      signature_fragment[hash_start:hash_end] = buffer

    return TryteString.from_trits(signature_fragment)
Ejemplo n.º 7
0
    def test_squeeze_multiple_hashes(self):
        """
    Squeezing more than 1 hash from the sponge.
    """
        # noinspection SpellCheckingInspection
        input_ = ('EMIDYNHBWMBCXVDEFOFWINXTERALUKYYPPHKP9JJ'
                  'FGJEIUY9MUDVNFZHMMWZUYUSWAIOWEVTHNWMHANBH')

        trits = TryteString(input_).as_trits()

        curl = Curl()
        curl.absorb(trits)
        trits_out = []
        curl.squeeze(trits_out, length=486)

        trits_out = TryteString.from_trits(trits_out)

        # noinspection SpellCheckingInspection
        self.assertEqual(
            trits_out,
            'AQBOPUMJMGVHFOXSMUAGZNACKUTISDPBSILMRAGIG'
            'RXXS9JJTLIKZUW9BCJWKSTFBDSBLNVEEGVGAMSSMQ'
            'GSJWCCFQRHWKTSMVPWWCEGOMCNWFYWDZBEDBLXIFB'
            'HOTCKUMCANLSXXTNKSYNBMOSDDEYFTDOYIKDRJM',
        )
Ejemplo n.º 8
0
  def test_from_trits(self):
    """
    Converting a sequence of trit values into a TryteString.
    """
    trits = [
      0, 0, -1,
      -1, 1, 0,
      -1, 1, -1,
      0, 1, 0,
      0, 0, 0,
      1, 1, 0,
      0, 0, 0,
      1, 1, 0,
      0, 1, 0,
      1, 1, 0,
      -1, 0, -1,
      1, 0, 0,
      -1, -1, 1,
      1, 0, 0,
      1, 0, -1,
      -1, 1, 0,
      1, -1, 0,
      -1, 1, 0,
      0, 1, 0,
      0, 1, 0,
      -1, 1, 1,
      -1, 1, 0,
      0, -1, 1,
      1, 0, 0,
    ]

    self.assertEqual(
      binary_type(TryteString.from_trits(trits)),
      b'RBTC9D9DCDQAEASBYBCCKBFA',
    )
Ejemplo n.º 9
0
    def test_length(self):
        """
    Specifying different values for the ``length`` argument.
    """
        # noinspection SpellCheckingInspection
        input_ = ('G9JYBOMPUXHYHKSNRNMMSSZCSHOFYOYNZRSZMAAYWDYEIMVVOGKPJB'
                  'VBM9TDPULSFUNMTVXRKFIDOHUXXVYDLFSZYZTWQYTE9SPYYWYTXJYQ'
                  '9IFGYOLZXWZBKWZN9QOOTBQMWMUBLEWUEEASRHRTNIQWJQNDWRYLCA')

        trits = TryteString(input_).as_trits()

        curl = Curl()
        curl.absorb(trits, offset=0, length=486)
        curl.absorb(trits, offset=0, length=243)
        trits_out = []
        curl.squeeze(trits_out)

        trits_out = TryteString.from_trits(trits_out)

        # noinspection SpellCheckingInspection
        self.assertEqual(
            trits_out,
            'OTYHXEXJLCSMEY9LYCC9ASJXMORTLAYQEHRS9DAH'
            '9NR9DXLXYDGOVOBEL9LWRITLWPHPYPZDKXVPAPKUA',
        )
Ejemplo n.º 10
0
  def test_from_trits(self):
    """
    Converting a sequence of trit values into a TryteString.
    """
    trits = [
      0, 0, -1,
      -1, 1, 0,
      -1, 1, -1,
      0, 1, 0,
      0, 0, 0,
      1, 1, 0,
      0, 0, 0,
      1, 1, 0,
      0, 1, 0,
      1, 1, 0,
      -1, 0, -1,
      1, 0, 0,
      -1, -1, 1,
      1, 0, 0,
      1, 0, -1,
      -1, 1, 0,
      1, -1, 0,
      -1, 1, 0,
      0, 1, 0,
      0, 1, 0,
      -1, 1, 1,
      -1, 1, 0,
      0, -1, 1,
      1, 0, 0,
    ]

    self.assertEqual(
      binary_type(TryteString.from_trits(trits)),
      b'RBTC9D9DCDQAEASBYBCCKBFA',
    )
Ejemplo n.º 11
0
    def test_absorb_offset(self):
        """
    Passing an ``offset`` argument to :py:meth:`Curl.absorb`.
    """
        # noinspection SpellCheckingInspection
        input_ = ('G9JYBOMPUXHYHKSNRNMMSSZCSHOFYOYNZRSZMAAYWDYEIMVVOGKPJB'
                  'VBM9TDPULSFUNMTVXRKFIDOHUXXVYDLFSZYZTWQYTE9SPYYWYTXJYQ'
                  '9IFGYOLZXWZBKWZN9QOOTBQMWMUBLEWUEEASRHRTNIQWJQNDWRYLCA')

        trits = TryteString(input_).as_trits()

        curl = Curl()
        curl.absorb(trits, offset=243, length=486)
        curl.absorb(trits, offset=0, length=243)
        trits_out = []
        curl.squeeze(trits_out)

        trits_out = TryteString.from_trits(trits_out)

        # noinspection SpellCheckingInspection
        self.assertEqual(
            trits_out,
            'ZWNF9YOCAKC9CXQFYZDKXSSAZOCAZLEVEB9OZDJQ'
            'GWEULHUDY9RAWAT9GIUXTTUSYJEGNGQDVJCGTQLN9',
        )
Ejemplo n.º 12
0
 def timestamp_as_trytes(self):
     # type: () -> TryteString
     """
 Returns a TryteString representation of the transaction's
 timestamp.
 """
     # Note that we are padding to 27 _trits_.
     return TryteString.from_trits(trits_from_int(self.timestamp, pad=27))
Ejemplo n.º 13
0
 def last_index_as_trytes(self):
     # type: () -> TryteString
     """
 Returns a TryteString representation of the transaction's
 ``last_index`` value.
 """
     # Note that we are padding to 27 _trits_.
     return TryteString.from_trits(trits_from_int(self.last_index, pad=27))
Ejemplo n.º 14
0
    def get_digest(self):
        # type: () -> Digest
        """
    Generates the digest used to do the actual signing.

    Signing keys can have variable length and tend to be quite long,
    which makes them not-well-suited for use in crypto algorithms.

    The digest is essentially the result of running the signing key
    through a PBKDF, yielding a constant-length hash that can be used
    for crypto.
    """
        hashes_per_fragment = FRAGMENT_LENGTH // Hash.LEN

        key_fragments = self.iter_chunks(FRAGMENT_LENGTH)

        # The digest will contain one hash per key fragment.
        digest = [0] * HASH_LENGTH * len(key_fragments)

        for (i, fragment
             ) in enumerate(key_fragments):  # type: Tuple[int, TryteString]
            fragment_trits = fragment.as_trits()

            key_fragment = [0] * FRAGMENT_LENGTH
            hash_trits = []

            for j in range(hashes_per_fragment):
                hash_start = j * HASH_LENGTH
                hash_end = hash_start + HASH_LENGTH
                hash_trits = fragment_trits[
                    hash_start:hash_end]  # type: MutableSequence[int]

                for k in range(26):
                    sponge = Curl()
                    sponge.absorb(hash_trits)
                    sponge.squeeze(hash_trits)

                key_fragment[hash_start:hash_end] = hash_trits

            sponge = Curl()
            sponge.absorb(key_fragment)
            sponge.squeeze(hash_trits)

            fragment_start = i * FRAGMENT_LENGTH
            fragment_end = fragment_start + FRAGMENT_LENGTH

            digest[fragment_start:fragment_end] = hash_trits

        return Digest(TryteString.from_trits(digest), self.key_index)
Ejemplo n.º 15
0
  def test_from_trits_wrong_length_padded(self):
    """
    Automatically padding a sequence of trit values with length not
    divisible by 3 so that it can be converted into a TryteString.
    """
    trits = [
      0, 0, -1,
      -1, 1, 0,
      -1, 1, -1,
      0, 1, # 0, <- Oops, did you lose something?
    ]

    self.assertEqual(
      binary_type(TryteString.from_trits(trits)),
      b'RBTC',
    )
Ejemplo n.º 16
0
  def test_from_trits_wrong_length_padded(self):
    """
    Automatically padding a sequence of trit values with length not
    divisible by 3 so that it can be converted into a TryteString.
    """
    trits = [
      0, 0, -1,
      -1, 1, 0,
      -1, 1, -1,
      0, 1, # 0, <- Oops, did you lose something?
    ]

    self.assertEqual(
      binary_type(TryteString.from_trits(trits)),
      b'RBTC',
    )
def send_transaction(node_url, address, tag, messages, values):
    propose_bundle = ProposedBundle()

    # Setting output transaction ...
    txn_output = ProposedTransaction(
        address = Address(address),
        value = values,
        tag = Tag(tag),
        message = TryteString.from_string(messages)
    )

    propose_bundle.add_transaction(txn_output)
    propose_bundle.finalize()
    trytes = propose_bundle.as_tryte_strings()

    api = Iota(node_url)

    # Tips
    trunk_hash, branch_hash = gtta(node_url)

    for tx_tryte in trytes:
        # Attachment timestamp insert
        timestamp = TryteString.from_trits(
            trits_from_int(int(time.time() * 1000), pad=27))
        tx_tryte = insert_to_trytes(2619, 2628, str(timestamp), tx_tryte)

        # timestamp_lower_bound = MIN_VALUE
        # timestamp_upper_bound = MAX_VALUE
        tx_tryte = insert_to_trytes(2637, 2646, str("MMMMMMMMM"), tx_tryte)

        # Tips insert - trunk
        tx_tryte = insert_to_trytes(2430, 2511, str(trunk_hash), tx_tryte)
        # Tips insert - branch
        tx_tryte = insert_to_trytes(2511, 2592, str(branch_hash), tx_tryte)

        # Do PoW for this transaction
        tx_tryte = attach_to_tangle(node_url, trunk_hash, branch_hash, tx_tryte)

        # Prepare to store and broadcast ...
        try:
            api.broadcast_and_store(tx_tryte)
        except Exception as e:
            return str("Error: %s" % (str(e)))

        return str(propose_bundle.hash)
Ejemplo n.º 18
0
  def test_squeeze_offset(self):
    """
    Passing an ``offset`` argument to :py:meth:`Curl.squeeze`.

    Example use case:
    https://github.com/iotaledger/iri/blob/v1.4.1.6/src/main/java/com/iota/iri/hash/ISS.java#L83
    """
    # noinspection SpellCheckingInspection
    input_ = (
      'CDLFODMOGMQAWXDURDXTUAOO9BFESHYGZLBUWIIHPTLNZCUNHZAAXSUPUIBW'
      'IRLOVKCVWJSWEKRJQZUVRDZGZRNANUNCSGANCJWVHMZMVNJVUAZNFZKDAIVV'
      'LSMIM9SVGUHYECTGGIXTAMXXO9FIXUMQFZCGRQWAOWJPBTXNNQIRSTZEEAJV'
      'FSXWTHWBQJCWQNYYMHSPCYRA99ITVILYJPMFGOGOUOZUVABK9HMGABSORCVD'
      'FNGLMPJ9NFKBWCZMFPIWEAGRWPRNLLG9VYUUVLCTEWKGWQIRIJKERZWC9LVR'
      'XJEXNHBNUGEGGLMWGERKYFB9YEZCLXLKKMCGLRKQOGASDOUDYEDJLMV9BHPG'
      'GCXQIUVUOFFXKEIIINLVWLRYHHLKXPLSTWKIKNEJWEDFQQFXQVEHGRCIJC9T'
      'GVQNPPKGCFGPJNWSCPQZDDSIGAVZEIVYJDVPUOCTEMKTZFGXNGPQCOIBD9MX'
      'YTHJTX'
    )

    trits = TryteString(input_).as_trits()
    curl = Curl()

    trits_out = [0] * 243
    for i in range(6):
      curl.reset()
      curl.absorb(trits, i * 243, (i + 1) * 243)
      curl.squeeze(trits, i * 243)

    curl.reset()
    curl.absorb(trits)
    curl.squeeze(trits_out)

    trits_out = TryteString.from_trits(trits_out)

    # noinspection SpellCheckingInspection
    self.assertEqual(
      trits_out,

      'TAWDGNSEAD9ZRGBBVRVEKQYYVDOKHYQ9KEIYJKFT'
      'BQEYZDWZVMRFJQQGTMPHBZOGPIJCCVWLZVDKLAQVI',
    )
Ejemplo n.º 19
0
def new_seed(old_seed_trytes, used_addresses_int):
    old_seed_int = int_from_trits(TryteString(old_seed_trytes).as_trits())
    old_seed_int += used_addresses_int
    return TryteString.from_trits(trits_from_int(old_seed_int))
Ejemplo n.º 20
0
def int_to_trytestring(int_input, length):
    trits = trits_from_int(int(int_input))
    trytes = TryteString.from_trits(trits)
    if len(trytes) < length:
        trytes += '9' * (length - len(trytes))
    return trytes
Ejemplo n.º 21
0
    while True:

        print("Create your Message ")
        Message = input()
        print("Create your Tag ")
        TAG = input()
        print("Please type in the secret Key:")
        secret_key = input()

        ## Create next root_address
        astrits = TryteString(str(root_address).encode()).as_trits()
        checksum_trits = []
        sponge = Kerl()
        sponge.absorb(astrits)
        sponge.squeeze(checksum_trits)
        result = TryteString.from_trits(checksum_trits)
        new_address = Address(result)

        ## transforming the secret_key into Base64 Key
        h = blake2b(digest_size=16)
        h_pw = h.update(bytes(secret_key.encode('utf-8')))
        hh = h.hexdigest()
        pw_string = str(hh).encode('utf-8')
        b64_pw = base64.b64encode(pw_string)

        ## Encrypt the Message
        data = {'message': Message}
        msg = json.dumps(data)
        key = b64_pw
        f = Fernet(key)
        token = f.encrypt(bytes(msg.encode('utf-8')))
Ejemplo n.º 22
0
def H(msg):
    out = []
    sponge = Curl()
    sponge.absorb(TryteString(msg).as_trits())
    sponge.squeeze(out)
    return TryteString.from_trits(out)
Ejemplo n.º 23
0
def send_transfer(tag, messages, address, values, dict_tips, debug=0):
    # Initialize PoW Library
    PoWlib = PoW_load_library(DCURL_PATH)
    PoW_interface_init(PoWlib)

    # Set output transaction
    print("Start to transfer ... ")
    time_start_send = time.time()

    propose_bundle = iota.ProposedBundle()

    print("Setting output transaction ...")
    txn_output = iota.ProposedTransaction(
        address=iota.Address(address),
        value=values,
        tag=iota.Tag(tag),
        message=TryteString.from_unicode(messages)
    )

    propose_bundle.add_transaction(txn_output)

    # Get input address
    if int(values) > 0:
        print("DEBUG values = %s" % (str(values)))

        print("Checking input balance ...")

        dict_inputs = api.get_inputs()
        if int(dict_inputs['totalBalance']) < int(values):
            print("Balance not enough")
            return 0

    # Setting intput transaction
    if int(values) > 0:
        print("Setting input transaction ...")
        value_input = 0
        index_input = 0
        while (int(value_input) < int(values)):
            addy = iota.Address(dict_inputs['inputs'][index_input])
            addy.balance = dict_inputs['inputs'][index_input].balance
            addy.key_index = dict_inputs['inputs'][index_input].key_index
            addy.security_level = TXN_SECURITY_LEVEL

            propose_bundle.add_inputs([addy])
            value_input = value_input + int(dict_inputs['inputs'][0].balance)

        # Send unspent inputs to
        print("Setting unspent input to a new address ...")
        unspent = iota.Address(generate_address()['addresses'][0])
        propose_bundle.send_unspent_inputs_to(unspent)

    # This will get the bundle hash
    print("Bundle finalize ...")

    time_start_bundle_finz = time.time()
    propose_bundle.finalize()
    time_end_bundle_finz = time.time()
    elapsed_bundle_finz = time_end_bundle_finz - time_start_bundle_finz

    # Signing
    # If the transaction need sign, it will then sign-up the transaction
    # to fill up signature fragements
    if int(values) > 0:
        print("Signing...")
        propose_bundle.sign_inputs(iota.crypto.signing.KeyGenerator(SEED))

    trytes = propose_bundle.as_tryte_strings()

    # Get tips by getTransactionsToApprove
    trunk_hash = dict_tips['trunkTransaction']
    branch_hash = dict_tips['branchTransaction']

    # Do PoW (attach to tangle)
    elapsed_pow = 0
    time_start_pow = time.time()
    for tx_tryte in trytes:
        # Attachment timestamp insert
        timestamp = TryteString.from_trits(
            trits_from_int(int(time.time() * 1000), pad=27))
        tx_tryte = insert_to_trytes(2619, 2628, str(timestamp), tx_tryte)
        # timestamp_lower_bound = MIN_VALUE
        # timestamp_upper_bound = MAX_VALUE
        tx_tryte = insert_to_trytes(2637, 2646, str("MMMMMMMMM"), tx_tryte)

        # Tips insert - trunk
        tx_tryte = insert_to_trytes(2430, 2511, str(trunk_hash), tx_tryte)
        # Tips insert - branch
        tx_tryte = insert_to_trytes(2511, 2592, str(branch_hash), tx_tryte)

        # Do PoW for this transaction
        print("Do POW for this transaction ...")

        nonce = PoW_interface_search(PoWlib, tx_tryte, MWM)
        tx_tryte = insert_to_trytes(2646, 2673, str(nonce), tx_tryte)

        time_end_pow = time.time()
        elapsed_pow = elapsed_pow + (time_end_pow - time_start_pow)

        # Update previous tx hash for next transaction
        trunk_hash = Transaction.from_tryte_string(tx_tryte[0:2673]).hash

        print("Prepare to store and broadcast ...")
        try:
            api.broadcast_and_store([tx_tryte[0:2673]])
        except Exception as e:
            print("Error: %s" % (str(e.context)))

    time_end_send = time.time()
    elapsed_send = time_end_send - time_start_send

    if debug == 1:
        data = [{'platform': 'pi3', 'total_time': str(elapsed_send), 'elapsed_pow': str(
            elapsed_pow), 'elqpsed_bundle_finished': str(elapsed_bundle_finz)}]
        json_data = json.dumps(data)
        print(json_data)

#        attach_debug_message_to_tangle(json_data)
    obj_txn = api.find_transactions(bundles=[propose_bundle.hash])
    return str(obj_txn['hashes'][0])
Ejemplo n.º 24
0
def hash(trytes):
    curl = Curl()
    curl.absorb(trytes.as_trits())
    trits_out = []
    curl.squeeze(trits_out)
    return TryteString.from_trits(trits_out)