Ejemplo n.º 1
0
  def test_trytes_contents_invalid(self):
    """
    ``trytes`` is an array, but it contains invalid values.
    """
    self.assertFilterErrors(
      {
        'trytes': [
          b'',
          True,
          None,
          b'not valid trytes',

          # This is actually valid; I just added it to make sure the
          # filter isn't cheating!
          TryteString(self.trytes2),

          2130706433,

          b'9' * (TransactionTrytes.LEN + 1),
        ],
      },

      {
        'trytes.0': [f.NotEmpty.CODE_EMPTY],
        'trytes.1': [f.Type.CODE_WRONG_TYPE],
        'trytes.2': [f.Required.CODE_EMPTY],
        'trytes.3': [Trytes.CODE_NOT_TRYTES],
        'trytes.5': [f.Type.CODE_WRONG_TYPE],
        'trytes.6': [Trytes.CODE_WRONG_FORMAT],
      },
    )
Ejemplo n.º 2
0
    def Receive(self, Start, Stop):
        Data_From_Node = False
        try:
            Data_From_Node = self.IOTA_Api.get_account_data(start = Start, stop = Stop)
        except:
            if "[Errno 111] Connection refused" in str(sys.exc_info()[1]):
                print("Connection error, finding an alternative node...") #< ----------------------------------------------------

            elif "certificate verify failed" in str(sys.exc_info()[1]):
                print("Node does not have a valid SSL certificate, finding an alternative node...") #< ----------------------------------------------------

            elif "[Errno 61] Connection refused" in str(sys.exc_info()[1]):
                print("Connection error, finding an alternative node...") #< ----------------------------------------------------

            else:
                print("Unexpected exception caught in receive") #< ----------------------------------------------------
                print(sys.exc_info()[1]) #< ----------------------------------------------------

        if Data_From_Node != False:
            Complete_Collection = {}
            for bundles in Data_From_Node["bundles"]:
                    for JSON in bundles.as_json_compatible():
                        temp = {}
                        temp["ReceiverAddress"] = str(JSON.get("address"))
                        temp["Tokens"] = JSON.get("value")
                        temp["Timestamp"] = JSON.get("attachment_timestamp")
                        temp["Message"] = bundles.get_messages()[0]
                        try:
                            temp["Message_Tag"] = TryteString(str(JSON.get("tag"))).decode()
                        except:
                            temp["Message_Tag"] = JSON.get("tag")
                        Complete_Collection[str(JSON.get("bundle_hash"))] = temp
            Data_From_Node = Complete_Collection
        return Data_From_Node
Ejemplo n.º 3
0
    def setUp(self):
        super(GetPrivateKeysCommandTestCase, self).setUp()

        self.adapter = MockAdapter()
        self.command = GetPrivateKeysCommand(self.adapter)

        #
        # Create a few tryte sequences we can reuse across tests.
        #
        # Note that these are not realistic values for private keys (a real
        # private key's length is a multiple of 2187 trytes), but we're
        # going to mock the KeyGenerator functionality anyway, so we just
        # need something that's short enough to be easy to compare.
        #
        self.trytes1 = TryteString(b'KEYONE', pad=FRAGMENT_LENGTH)
        self.trytes2 = TryteString(b'KEYTWO', pad=FRAGMENT_LENGTH)
Ejemplo n.º 4
0
    def test_decode(self):
        """
    Converting a sequence of trytes into a Unicode string.
    """
        trytes = TryteString(b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD')

        self.assertEqual(trytes.decode(), '你好,世界!')
Ejemplo n.º 5
0
 def test_as_trytes_mulitple_trytes(self):
     """
 Converting a multiple-tryte TryteString into a sequence of
 tryte values.
 """
     self.assertListEqual(
         TryteString(b'ZJVYUGTDRPDYFGFXMK').as_trytes(),
         [
             [-1, 0, 0],
             [1, 0, 1],
             [1, 1, -1],
             [1, -1, 0],
             [0, 1, -1],
             [1, -1, 1],
             [-1, 1, -1],
             [1, 1, 0],
             [0, 0, -1],
             [1, -1, -1],
             [1, 1, 0],
             [1, -1, 0],
             [0, -1, 1],
             [1, -1, 1],
             [0, -1, 1],
             [0, -1, 0],
             [1, 1, 1],
             [-1, 1, 1],
         ],
     )
Ejemplo n.º 6
0
    def test_encode(self):
        """
    Converting a sequence of trytes into a sequence of bytes.
    """
        trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')

        self.assertEqual(trytes.encode(), b'Hello, IOTA!')
Ejemplo n.º 7
0
 def test_init_error_invalid_characters(self):
     """
 Attempting to reset a TryteString with a value that contains
 invalid characters.
 """
     with self.assertRaises(ValueError):
         TryteString(b'not valid')
Ejemplo n.º 8
0
 def test_init_from_unicode_string_error_not_ascii(self):
     """
 Attempting to initialize a TryteString from a unicode string that
 contains non-ASCII characters.
 """
     with self.assertRaises(UnicodeEncodeError):
         TryteString('¡Hola, IOTA!')
Ejemplo n.º 9
0
    def test_fail_tips_contents_invalid(self):
        """
    ``tips`` contains invalid values.
    """
        self.assertFilterErrors(
            {
                'tips': [
                    b'',
                    True,
                    None,
                    b'not valid trytes',

                    # This is actually valid; I just added it to make sure the
                    # filter isn't cheating!
                    TryteString(self.trytes1),
                    2130706433,
                    b'9' * 82,
                ],
                'transactions': [TransactionHash(self.trytes1)],
            },
            {
                'tips.0': [f.Required.CODE_EMPTY],
                'tips.1': [f.Type.CODE_WRONG_TYPE],
                'tips.2': [f.Required.CODE_EMPTY],
                'tips.3': [Trytes.CODE_NOT_TRYTES],
                'tips.5': [f.Type.CODE_WRONG_TYPE],
                'tips.6': [Trytes.CODE_WRONG_FORMAT],
            },
        )
Ejemplo n.º 10
0
    def test_fail_inputs_contents_invalid(self):
        """
    ``inputs`` is a non-empty array, but it contains invalid values.
    """
        self.assertFilterErrors(
            {
                'inputs': [
                    b'',
                    True,
                    None,
                    b'not valid trytes',

                    # This is actually valid; I just added it to make sure the
                    #   filter isn't cheating!
                    TryteString(self.trytes4),
                    2130706433,
                    b'9' * 82,
                ],
                'depth':
                100,
                'minWeightMagnitude':
                18,
                'seed':
                Seed(self.trytes1),
                'transfers': [self.transfer1],
            },
            {
                'inputs.0': [f.Required.CODE_EMPTY],
                'inputs.1': [f.Type.CODE_WRONG_TYPE],
                'inputs.2': [f.Required.CODE_EMPTY],
                'inputs.3': [Trytes.CODE_NOT_TRYTES],
                'inputs.5': [f.Type.CODE_WRONG_TYPE],
                'inputs.6': [Trytes.CODE_WRONG_FORMAT],
            },
        )
Ejemplo n.º 11
0
    def test_fail_addresses_contents_invalid(self):
        """
    ``addresses`` is an array, but it contains invalid values.
    """
        self.assertFilterErrors(
            {
                'addresses': [
                    b'',
                    text_type(self.trytes1, 'ascii'),
                    True,
                    None,
                    b'not valid trytes',

                    # This is actually valid; I just added it to make sure the
                    # filter isn't cheating!
                    TryteString(self.trytes2),
                    2130706433,
                    b'9' * 82,
                ],
            },
            {
                'addresses.0': [f.Required.CODE_EMPTY],
                'addresses.1': [f.Type.CODE_WRONG_TYPE],
                'addresses.2': [f.Type.CODE_WRONG_TYPE],
                'addresses.3': [f.Required.CODE_EMPTY],
                'addresses.4': [Trytes.CODE_NOT_TRYTES],
                'addresses.6': [f.Type.CODE_WRONG_TYPE],
                'addresses.7': [Trytes.CODE_WRONG_FORMAT],
            },
        )
Ejemplo n.º 12
0
    def test_container_error_wrong_type(self):
        """
    Checking whether a TryteString contains a sequence with an
    incompatible type.
    """
        trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')

        with self.assertRaises(TypeError):
            # TryteString is not a numeric type, so this makes about as much
            # sense as ``16 in b'Hello, world!'``.
            16 in trytes

        with self.assertRaises(TypeError):
            # This is too ambiguous.  Is this a list of trit values that can
            # appar anywhere in the tryte sequence, or does it have to match
            # a tryte exactly?
            [0, 1, 1, 0, -1, 0] in trytes

        with self.assertRaises(TypeError):
            # This makes more sense than the previous example, but for
            # consistency, we will not allow checking for trytes inside
            # of a TryteString.
            [[0, 0, 0], [1, 1, 0]] in trytes

        with self.assertRaises(TypeError):
            # Did I miss something? When did we get to DisneyLand?
            None in trytes
Ejemplo n.º 13
0
 def checkStatus(self):
     today = datetime.datetime.now()
     todayCheck = today.strftime("%d-%m-%Y")
     initialTime = self.initialTime
     logEntry = 'Checking for incoming missiles...\n'
     self.updateLog(logEntry)
     txCommand = {
         "command": "findTransactions",
         "addresses": [self.fleetAddress]
     }
     findTx = json.dumps(txCommand)
     headers = {
         'content-type': 'application/json',
         'X-IOTA-API-Version': '1'
     }
     try:
         requestFindTx = requests.post(url=self.nodeURL,
                                       data=findTx,
                                       headers=headers)
         jsonDataTx = json.loads(requestFindTx.text)
         tryteCommand = {
             "command": "getTrytes",
             "hashes": jsonDataTx['hashes']
         }
     except:
         messagebox.showinfo("Error", "The address is invalid!")
     findTrytes = json.dumps(tryteCommand)
     requestTrytes = requests.post(url=self.nodeURL,
                                   data=findTrytes,
                                   headers=headers)
     jsonDataTrytes = json.loads(requestTrytes.content)
     for item in jsonDataTrytes['trytes']:
         tryteString = TryteString(item).decode(errors='ignore',
                                                strip_padding=False)
         head = tryteString.split(';')
         content = head[0].split(',')
         for data in content:
             if data == todayCheck:
                 if datetime.datetime.strptime(
                         content[3],
                         '%H:%M:%S') >= datetime.datetime.strptime(
                             initialTime, '%H:%M:%S'):
                     self.incomingTime.append(content[3])
                     if len(self.incomingTime) > 1:
                         if len(set(self.incomingTime)) == self.session:
                             if datetime.datetime.strptime(
                                     content[3], '%H:%M:%S'
                             ) == datetime.datetime.strptime(
                                     max(set(self.incomingTime)),
                                     '%H:%M:%S'):
                                 self.session += 1
                                 self.displayIncoming(
                                     content[0], content[1])
                                 self.displayHitResponse(
                                     content[4], content[5], content[6])
                                 break
                     else:
                         self.session += 1
                         self.displayIncoming(content[0], content[1])
Ejemplo n.º 14
0
 def test_ascii_bytes(self):
     """
 Getting an ASCII representation of a TryteString, as bytes.
 """
     self.assertEqual(
         binary_type(TryteString(b'HELLOIOTA')),
         b'HELLOIOTA',
     )
Ejemplo n.º 15
0
  def test_as_string_strip(self):
    """
    Strip trailing padding from a TryteString before converting.
    """
    # Note odd number of trytes!
    trytes = TryteString(b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD9999999999999')

    self.assertEqual(trytes.as_string(), '你好,世界!')
Ejemplo n.º 16
0
 def test_fail_wrong_type(self):
     """The incoming value has an incompatible type."""
     self.assertFilterErrors(
         # Use ``FilterRepeater(Trytes)`` to validate a sequence of tryte
         #   representations.
         [TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')],
         [f.Type.CODE_WRONG_TYPE],
     )
Ejemplo n.º 17
0
    def test_pass_tryte_string(self):
        """The incoming value is a TryteString."""
        trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')

        filter_ = self._filter(trytes)

        self.assertFilterPasses(filter_, trytes)
        self.assertIsInstance(filter_.cleaned_data, TryteString)
Ejemplo n.º 18
0
 def test_ascii_str(self):
     """
 Getting an ASCII representation of a TryteString, as a unicode
 string.
 """
     self.assertEqual(
         text_type(TryteString(b'HELLOIOTA')),
         'HELLOIOTA',
     )
Ejemplo n.º 19
0
def call_dcurl(idx, mwm, lib, trytes_list):
    tmp = str(trytes_list[idx]).encode('ascii')
    ret = lib.dcurl_entry(tmp, mwm)
    trytes = TryteString(ret)

    hash_trytes = hash(trytes)
    RESULT_TX.append(hash_trytes)

    join_list[idx].release()
Ejemplo n.º 20
0
    def test_as_bytes_partial_sequence_errors_strict(self):
        """
    Attempting to convert an odd number of trytes into bytes using the
    `as_bytes` method with errors='strict'.
    """
        trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA9')

        with self.assertRaises(TrytesDecodeError):
            trytes.as_bytes(errors='strict')
Ejemplo n.º 21
0
 def GetTransactionMessage(self, TID):
     bundle = self.api.get_bundles(TID)
     for x in bundle['bundles']:
         for txn in x:
             Vtxn = vars(txn)
             if Vtxn['hash'] != TID:
                 continue
             TryteStringMessage = str(Vtxn['signature_message_fragment'])
             return TryteString(str.encode(TryteStringMessage)).decode()
Ejemplo n.º 22
0
    def test_as_bytes_non_ascii_errors_strict(self):
        """
    Converting a sequence of trytes into bytes using the `as_bytes`
    method yields non-ASCII characters, and errors='strict'.
    """
        trytes = TryteString(b'ZJVYUGTDRPDYFGFXMK')

        with self.assertRaises(TrytesDecodeError):
            trytes.as_bytes(errors='strict')
Ejemplo n.º 23
0
def PoW_interface_search(lib, tryte, mwm):
    if lib is not None:
        # Do the PoW
        ctryte = str(tryte).encode('ascii')
        ret = lib.dcurl_entry(ctryte, mwm)

        # Get the nonce
        ret_tryte = TryteString(ret[:2673])
        return str(ret_tryte[-27:])
Ejemplo n.º 24
0
  def test_as_string_no_strip(self):
    """
    Prevent stripping trailing padding when converting to string.
    """
    trytes = TryteString(b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD999999999999')

    self.assertEqual(
      trytes.as_string(strip_padding=False),
      '你好,世界!\x00\x00\x00\x00\x00\x00',
    )
Ejemplo n.º 25
0
def put_action():
    req_json = request.get_json()

    if req_json is None:
        return 'request error'

    msg = Fragment(TryteString(req_json['ipfs_addr']))
    ipfs_addr = msg.decode()
    wasm.exec_action(ipfs_addr)
    return 'ok'
Ejemplo n.º 26
0
    def test_string_conversion(self):
        """
    A TryteString can be converted into an ASCII representation.
    """
        self.assertEqual(
            binary_type(TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')),

            # Note that the trytes are NOT converted into bytes!
            b'RBTC9D9DCDQAEASBYBCCKBFA',
        )
Ejemplo n.º 27
0
def convert(data, salt):
    OUTPUT_SIZE = 80  # Number of characters to fit IOTA address
    hash_shake = sha3.shake_128()
    if salt is None:
        hash_shake.update(data.encode())
    else:
        hash_shake.update(data.encode() + salt.encode())
    msg_trytes = TryteString.from_unicode(
        hash_shake.hexdigest(int(OUTPUT_SIZE / 4))) + TryteString(b'9')
    return Address(msg_trytes)
Ejemplo n.º 28
0
def trailing_zeros(trytes):
    trytes = TryteString(trytes)
    trits = trytes.as_trits()
    n = len(trits) - 1
    z = 0
    for i in range(0, n):
        if trits[n - i] == 0:
            z += 1
        else:
            break
    return z
Ejemplo n.º 29
0
    def test_as_bytes_non_ascii_errors_replace(self):
        """
    Converting a sequence of trytes into bytes using the `as_bytes`
    method yields non-ASCII characters, and errors='replace'.
    """
        trytes = TryteString(b'ZJVYUGTDRPDYFGFXMK')

        self.assertEqual(
            trytes.as_bytes(errors='replace'),
            b'??\xd2\x80??\xc3??',
        )
Ejemplo n.º 30
0
    def test_encode_non_ascii_errors_ignore(self):
        """
    Converting a sequence of trytes into bytes using the `encode`
    method yields non-ASCII characters, and errors='ignore'.
    """
        trytes = TryteString(b'ZJVYUGTDRPDYFGFXMK')

        self.assertEqual(
            trytes.encode(errors='ignore'),
            b'\xd2\x80\xc3',
        )