Ejemplo n.º 1
0
def createDatamapGenerator(startingHash, n, offset=None):
	"""Creates a generator that yields the iota addresses for each iteration, starting with `startingHash` up to `n` iterations.
	
	Arguments:
		startingHash {bytes} -- Self-explanatory.
		n {int} -- Max number of iterations. If None, there's no max number of itera

	Keyword Arguments:
		offset {int} -- Number of hashes to skip before returning the generator. Ex: startingHash is the genHash, but you want the first address in the generator to be the 3rd in the datamap, so the offset must be 2.

	Yields:
		iota.types.TryteString -- Iota address corresponding to the current hash.
	"""
	nextHash = startingHash
	if offset is not None:
		for _ in range(offset):
			nextHash = hashlib.sha256(nextHash).digest()
	if n is None:
		while True:
			obfuscatedhash = hashlib.sha384(nextHash).digest()
			address = TryteString.from_bytes(obfuscatedhash)[0:81]
			nextHash = hashlib.sha256(nextHash).digest()
			yield address
	else:
		for _ in range(n):
			obfuscatedhash = hashlib.sha384(nextHash).digest()
			address = TryteString.from_bytes(obfuscatedhash)[0:81]
			nextHash = hashlib.sha256(nextHash).digest()
			yield address
Ejemplo n.º 2
0
 def test_from_bytes(self):
     """
 Converting a sequence of bytes into a TryteString.
 """
     self.assertEqual(
         binary_type(TryteString.from_bytes(b'Hello, IOTA!')),
         b'RBTC9D9DCDQAEASBYBCCKBFA',
     )
Ejemplo n.º 3
0
 def test_from_bytes(self):
   """
   Converting a sequence of bytes into a TryteString.
   """
   self.assertEqual(
     binary_type(TryteString.from_bytes(b'Hello, IOTA!')),
     b'RBTC9D9DCDQAEASBYBCCKBFA',
   )
Ejemplo n.º 4
0
def compress_str(data):
    if enable_compression == True:
        out = StringIO.StringIO()
        with gzip.GzipFile(fileobj=out, mode="w") as f:
            f.write(data)
        compressed_data = out.getvalue()
        return TryteString.from_bytes(compressed_data).__str__()
    else:
        return data
Ejemplo n.º 5
0
    def test_from_bytes_random(self):
        """
    Generating a TryteString from a sequence of random bytes.
    """
        bytes_ = urandom(81)
        trytes = TryteString.from_bytes(bytes_)

        # We can't predict exactly what the result will be, but we can at
        # least verify that the bytes were correctly interpreted, and no
        # errors were generated.
        self.assertEqual(trytes.as_bytes(), bytes_)
Ejemplo n.º 6
0
 def cache_txn_in_tangle_simple(self, data, tag):
     address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
     txns = self.api.get_transactions_to_approve(self.depth)
     tr = self.api.get_trytes([txns[u'branchTransaction']])
     txn = Transaction.from_tryte_string(tr[u'trytes'][0], txns[u'branchTransaction'])
     txn.trunk_transaction_hash = txns[u'trunkTransaction']
     txn.branch_transaction_hash = txns[u'branchTransaction']
     txn.tag = Tag(TryteString.from_string(tag))
     txn.signature_message_fragment = Fragment(TryteString.from_bytes(data))
     attach_trytes = attachToTangle(self.uri, txns[u'trunkTransaction'].__str__(), txns[u'branchTransaction'].__str__(), 1, txn.as_tryte_string().__str__())
     res = self.api.broadcast_and_store(attach_trytes[u'trytes'])
     return res
Ejemplo n.º 7
0
    def emit(self, message):
        datum = self.encrypt(json.dumps([time.time(), message]))
        tx = ProposedTransaction(address=Address(self.address),
                                 value=0,
                                 message=TryteString.from_bytes(datum))
        startTime = time.time()
        print(f"Sending datum: {datum}")
        try:
            bundle = self.api.send_transfer(transfers=[tx])['bundle']
        except adapter.BadApiResponse as e:
            print("Bad response from server. Failed to send. Retry")
            return self.emit(message)

        duration = time.time() - startTime
        reference = bundle.transactions[0].hash
        print(f'Sent in {duration:.01f} secconds to {reference}')
Ejemplo n.º 8
0
    def send_to_iota(node: str, transactions: List[Transaction], local_pow: bool = False) -> str:
        """send json type data to IOTA

        Args:
            node (str): IOTA node
            transactions (List[Transaction]): transactions
            local_pow (bool, optional): local pow, might failed. Defaults to False.

        Returns:
            str: transaction hash
        """
        logger.info(f"[SEND TO IOTA] Data: {transactions}")
        # Prepare transactions
        transfers = [
            ProposedTransaction(
                address=Address(transaction.address),
                message=TryteString.from_bytes(json.dumps(transaction.message).encode()),
                tag=Tag(transaction.tag.replace("_", "9")),
                value=0,
            )
            for transaction in transactions
        ]
        # Create adapter
        logger.info(f"[SEND TO IOTA] IOTA node: {node}")
        api = iota(adapter=node, local_pow=local_pow)
        # Send transactions to IOTA
        logger.info("[SEND TO IOTA] Sending...")
        bundle_result = api.send_transfer(transfers=transfers)["bundle"]
        logger.info("[SEND TO IOTA]            Done")
        # Transaction hash
        logger.info(
            f"[SEND TO IOTA] Transaction hash: {bundle_result.transactions[0].hash}, Bundle hash: {bundle_result.hash}"
        )
        # Show bundle result
        logger.debug(bundle_result.as_json_compatible())
        return str(bundle_result.transactions[0].hash)
Ejemplo n.º 9
0
def sign_message(message, private_key):
    signature_base_64 = sign(private_key, SHA256.new(message))
    return TryteString.from_bytes(signature_base_64)
Ejemplo n.º 10
0
def send_iota(data_crypt, data_summary, api, address):
    #FUNCION EMPLEADA PARA MANDAR LA TRANSACCION DE VALOR CERO A LA RED.

    data_def = ''
    #SE DECLARA UN STRING DONDE GUARDAREMOS CONSECUTIVAMENTE TODA LA INFORMACION
    #CIFRADA DE LOS CLIENTES. EL METODO DE ENCRIPTACION PERMITIRA SEPARARLO SIN
    #PROBLEMAS, COMO SE VE EN ESTE APARTADO, EN Lectura de datos de la red.

    t0 = time.time()
    #REGISTRO DE TIEMPO PARA LLEVAR UN CONTROL DEL PROCESO

    for i in range(3):
        #BUCLE EMPLEADO PARA CIFRAR CON LA CLAVE PUBLICA DE CADA CLIENTE SU PARTE
        #CORRESPONDIENTE DE LA LISTA data_crypt, QUE SE HA DEFINIDO EN LA OTRA FUNCION.

        path = '/home/pi/Documents/FJavierGb/ULTIMATES/Public_Key'
        path1 = path + str(i)
        path2 = path1 + '.py'
        #SISTEMA VASTO PARA ABRIR EL DOCUMENTO DONDE SE GUARDA LA LLAVE PUBLICA
        #DE CADA CLIENTE DENTRO DE LA RASPBERRY. LA DIRECCION DEBE SER FIJA UNA
        #VEZ SE IMPLANTE EL SISTEMA EN UN DISPOSITIVO.

        public_key = open(path2, 'r')
        pubk = public_key.read()
        #FUNCIONES EMPLEADAS PARA ABRIR Y GUARDAR EN LA VARIABLE pubk LA CLAVE
        #PUBLICA DEL CLIENTE ESPECIFICO EN CADA ITERACION.

        pubk1 = RSA.importKey(pubk)
        cipher1 = PKCS1_OAEP.new(pubk1)
        #FUNCIONES QUE PREPARAN EL ALGORITMO A UTILIZAR JUNTO A LA CLAVE PUBLICA
        #PARA ENCRIPTAR EL MENSAJE EN BYTES. VER APARTADO 3.3.

        data_crypt[i] = cipher1.encrypt(str(data_crypt[i]))
        #ENCRIPTA LA PARTE CORRESPONDIENTE DEL MENSAJE DE CADA CLIENTE CON SU
        #CLAVE PUBLICA. PREVIAMENTE, TODA LA LISTA QUE CORRESPONDE A CADA CLIENTE
        #SE TRANSFORMA EN UNA STRING PARA PODER CONVERTIRSE CORRECTAMENTE EN BYTES.

        public_key.close()
        #SE CIERRA EL DOCUMENTO DONDE SE ENCUENTRA LA LLAVE PUBLICA

        data_def = data_def + data_crypt[i]
        #UNE TODAS LAS PARTES ENCRIPTADAS EN UNA UNICA

    api.send_transfer(transfers=[
        ProposedTransaction(address=Address(address[0]),
                            message=TryteString.from_bytes(data_def),
                            tag=Tag(b'RPICTVFCOJAVIER'),
                            value=0,
                            timestamp=float(int(data_summary.iloc[5, 12])))
    ])
    #PAQUETE DE DATOS QUE ENVIAMOS AL NODO AL QUE ESTAMOS CONECTADOS. LOS ELEMENTOS
    #SE HAN EXPLICADO COMPLETAMENTE EN EL APARTADO 4.3. PERO CABE DESTACAR QUE
    #ES UNA TRANSACCION DE VALOR 0, QUE SE MANDA A NUESTRA PROPIA DIRECCION, QUE
    #SE EMPLEA UN TAG PROPIO DEL AUTOR Y QUE SE EMPLEA COMO TIMESTAMP LA FECHA
    #DE LA ULTIMA MEDIDA QUE SE TOMO DENTRO DEL DOCUMENTO.

    t1 = time.time()
    #REGISTRO DE TIEMPO PARA LLEVAR UN CONTROL DEL PROCESO
    t2 = t1 - t0
    #DIFERENCIA ENTRE AMBOS REGISTROS, QUE INDICA EL TIEMPO QUE HA TARDADO EN
    #REALIZARSE LA TRANSACCION.
    print('Enviado en:', t2)
Ejemplo n.º 11
0
json_data = json.dumps(data)

# Ask user for a password to use for encryption
password = getpass('Please supply a password for encryption:')

print('Encrypting data...')
# Encrypt data
# Note, that in Python 3, encrypt returns 'bytes'
cipher = encrypt(password, json_data)

# Encode to base64, output contains only ASCII chars
b64_cipher = b64encode(cipher)

print('Constructing transaction locally...')
# Convert to trytes
trytes_encrypted_data = TryteString.from_bytes(b64_cipher)

# Generate an address from your seed to post the transfer to
my_address = api.get_new_addresses(index=42)['addresses'][0]

# Tag is optional here
my_tag = Tag(b'CONFIDENTIALINFORMATION')

# Prepare a transaction object
tx = ProposedTransaction(
    address=my_address,
    value=0,
    tag=my_tag,
    message=trytes_encrypted_data,
)
Ejemplo n.º 12
0
def to_tryte_from_picture_trace(picture):
    enc_image = img_encode_trace(picture)
    tryte = TryteString.from_bytes(zlib.compress(enc_image))
    return tryte
Ejemplo n.º 13
0
    def post_to_tangle(self, data, mwm=14, address_level=1, verbose=False):
        """Posts data to the tangle to a randomly generated address

        :param data: Data to be stored on the tangle
        :param mwm: minimum weight magnitude for iota node, check default mwm of network
        :param address_level: Security level of address, 1-3
        :param verbose: Prints out the transaction process if True
        :return elapsed time: Time of the transaction
        """

        # Encrypt data before being posted to tangle
        if self.encrypt:
            data = self.crypto.encrypt(data)
            tryte_string = TryteString.from_bytes(data)
        else:
            tryte_string = TryteString.from_string(str(data))

        # Tracks how long the transaction takes
        start = time.time()

        # Gets an appropriate address for sending transaction
        if self.reuse_address:
            if self.address is '':
                # Generates a new unused address
                self.address = self.generate_address(address_level)
        else:
            self.address = self.generate_address(address_level)

        # Checks address to ensure there was no problem
        if self.address is None:
            self.post_to_tangle(data, mwm, address_level, verbose)

        if verbose:
            print("Transaction Initialised...")
            print("Sending to: ", self.address)

        try:
            # Posts data to the tangle
            self.api.send_transfer(
                depth=3,
                transfers=[
                    ProposedTransaction(
                        address=self.address,
                        value=0,
                        tag=self.tag,
                        message=tryte_string,
                    ),
                ],
                min_weight_magnitude=mwm,
            )

            # Time of transaction
            end = time.time()
            elapsed_time = end - start

            if verbose:
                print("Transaction complete \nElapsed time: ", elapsed_time, " seconds.")

            return elapsed_time

        except iota.BadApiResponse:
            print("Transaction failed, retrying...")
            self.post_to_tangle(data, mwm, address_level, verbose)
Ejemplo n.º 14
0
if __name__ == "__main__":


	input_data=input("Quel est votre data a envoyé ?")
	UID=input("Quel est votre tag de voiture ?") 

	#connexion to the devnet, from the seed 
	
	private_key=import_private_key(f'keys/car_{UID}_priv.pem')
	seed=import_file(f'seed_adress/seed_car_{UID}.txt')
	print(seed)
	api = Iota('https://nodes.devnet.iota.org:443', seed, testnet = True)
	address='B9UCJQA9AUNWWQCFKPHYPBXFCSZPKMQI9TWFN9G9BJTHBHZQDXFXTGTPICXFTYKGJKJR9TWLVMVZEVPJX'
	data=input_data.encode("utf-8")
	signature=sign(private_key,SHA256.new(data))
	print(signature)
	signature_trytes=TryteString.from_bytes(signature)
	message=TryteString.from_unicode(input_data)
	end=TryteString.from_unicode('?')
	message=message+signature_trytes+end
	tx = ProposedTransaction(
	address=Address(address),
	value = 10,
	tag=Tag(UID),
	message=message
	) 
	result = api.send_transfer(transfers=[tx] )
	print('Bundle: ')
	print(result['bundle'].tail_transaction.hash)