def test_as_string(self): """ Converting a sequence of trytes into a Unicode string. """ trytes = TryteString(b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD') self.assertEqual(trytes.as_string(), '你好,世界!')
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(), '你好,世界!')
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')
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')
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', )
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??', )
def test_as_bytes_partial_sequence_errors_replace(self): """ Attempting to convert an odd number of trytes into bytes using the `as_bytes` method with errors='replace'. """ trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA9') self.assertEqual( trytes.as_bytes(errors='replace'), # The extra tryte is replaced with '?'. b'Hello, IOTA!?', )
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)
def test_iter_chunks(self): """ Iterating over a TryteString in constant-size chunks. """ trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') self.assertListEqual( list(trytes.iter_chunks(9)), [ TryteString(b'RBTC9D9DC'), TryteString(b'DQAEASBYB'), # The final chunk is padded as necessary. TryteString(b'CCKBFA999'), ], )
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', )
def test_from_string(self): """ Converting a Unicode string into a TryteString. """ self.assertEqual( binary_type(TryteString.from_string('你好,世界!')), b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD', )
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', )
def test_random(self): """ Generating a random sequence of trytes. """ trytes = TryteString.random(Hash.LEN) # It is (hopefully!) impossible to predict what the actual trytes # will be, but at least we can verify that the correct number were # generated! self.assertEqual(len(trytes), Hash.LEN)
def test_as_string_not_utf8_errors_ignore(self): """ The tryte sequence does not represent a valid UTF-8 sequence, and errors='ignore'. """ # Chop off a couple of trytes to break up a multi-byte sequence. trytes = TryteString.from_string('你好,世界!')[:-2] self.assertEqual( trytes.as_string('ignore'), '你好,世界', )
def test_as_string_not_utf8_errors_strict(self): """ The tryte sequence does not represent a valid UTF-8 sequence, and errors='strict'. """ # Chop off a couple of trytes to break up a multi-byte sequence. trytes = TryteString.from_string('你好,世界!')[:-2] # Note the exception type. The trytes were decoded to bytes # successfully; the exception occurred while trying to decode the # bytes into Unicode code points. with self.assertRaises(UnicodeDecodeError): trytes.as_string('strict')
def test_as_string_not_utf8_errors_replace(self): """ The tryte sequence does not represent a valid UTF-8 sequence, and errors='replace'. """ # Chop off a couple of trytes to break up a multi-byte sequence. trytes = TryteString.from_string('你好,世界!')[:-2] self.assertEqual( trytes.as_string('replace'), # Note that the replacement character is the Unicode replacement # character, not '?'. '你好,世界�', )
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 test_add_transaction_short_message(self): """ Adding a transaction to a bundle, with a message short enough to fit inside a single transaction. """ # noinspection SpellCheckingInspection self.bundle.add_transaction(ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999AETEXB' b'D9YBTH9EMFKF9CAHJIAIKDBEPAMH99DEN9DAJETGN' ), message = TryteString.from_string('Hello, IOTA!'), value = 42, )) # We can fit the message inside a single fragment, so only one # transaction is necessary. self.assertEqual(len(self.bundle), 1)
def from_tryte_to_picture(tryte): from_trytes = zlib.decompress(TryteString.as_bytes(tryte)) dec_img = img_decode(from_trytes) return dec_img
# If null, a random seed will be generated. seed=b'SEED9GOES9HERE', ) # Example of sending a transfer using the sandbox. # For more information, see :py:meth:`Iota.send_transfer`. # noinspection SpellCheckingInspection iota.send_transfer( depth=100, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'), # Amount of IOTA to transfer. # This value may be zero. value=42, # Optional tag to attach to the transfer. tag=Tag(b'EXAMPLE'), # Optional message to include with the transfer. message=TryteString.from_string('Hello, Tangle!'), ), ], )
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, )
def test_slice_mutator(self): """ Modifying slices of a TryteString. """ ts = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') ts[4] = TryteString(b'A') self.assertEqual(ts, TryteString(b'RBTCAD9DCDQAEASBYBCCKBFA')) ts[:4] = TryteString(b'BCDE') self.assertEqual(ts, TryteString(b'BCDEAD9DCDQAEASBYBCCKBFA')) # The lengths do not have to be the same... ts[:-4] = TryteString(b'EFGHIJ') self.assertEqual(ts, TryteString(b'EFGHIJKBFA')) # ... unless you are trying to set a single tryte. with self.assertRaises(ValueError): ts[4] = TryteString(b'99') # Any TrytesCompatible value will work. ts[3:-3] = b'FOOBAR' self.assertEqual(ts, TryteString(b'EFGFOOBARBFA')) # I have no idea why you would ever need to do this, but I'm not # going to judge, either. ts[2:-2:2] = b'IOTA' self.assertEqual(ts, TryteString(b'EFIFOOTAABFA')) with self.assertRaises(IndexError): ts[42] = b'9' # To match the behavior of built-in types, TryteString will allow # you to modify a slice that occurs after the end of the sequence. ts[42:43] = TryteString(b'9') self.assertEqual(ts, TryteString(b'EFIFOOTAABFA9'))
def test_length(self): """ Just like byte strings, TryteStrings have length. """ self.assertEqual(len(TryteString(b'RBTC')), 4) self.assertEqual(len(TryteString(b'RBTC', pad=81)), 81)
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])
def hash(trytes): curl = Curl() curl.absorb(trytes.as_trits()) trits_out = [] curl.squeeze(trits_out) return TryteString.from_trits(trits_out)
def findTransactions(self, tag=None): logger.info("begin to load covid data") transactions = None if tag: transactions = api.find_transactions(addresses=[iotaAddress, ], tags=[tag, ]) else: transactions = api.find_transactions(addresses=[iotaAddress, ]) # transactions = api.find_transactions(tags=[covid19model_tag, ]) hashes = [] # Determine non-empty address-判断非空地址 if not transactions: logger.info("iotaAddress not exists") return [] else: logger.info("loading iotaAddress data...") for txhash in transactions['hashes']: hashes.append(txhash) if hashes: logger.info("transactions not empty") else: logger.info("transactions empty") return [] # Get Trytes accepts multiple Transaction Hashes trytes = api.get_trytes(hashes)['trytes'] # We need to get all trytes from all messages and put them in the right order # We do this by looking at the index of the transaction parts = [] for trytestring in trytes: tx = Transaction.from_tryte_string(trytestring) # logger.info(tx.current_index) parts.append((tx.current_index, tx.signature_message_fragment)) parts.sort(key=lambda x: x[0]) # All that's left is to concatenate and wrap the parts in a TryteString object full_message = TryteString.from_unicode('') resultMsgs = [] for index, part in parts: full_message += part # Constructed as CovidData-构造为CovidData try: cm = full_message.decode() # Add to result list-添加到结果列表 resultMsgs.append(cm) except iota.codecs.TrytesDecodeError: logger.exception("covid data analysis iota.codecs.TrytesDecodeError, data: " + full_message.decode()) continue except ValueError: logger.exception("covid data analysis ValueError, data: " + full_message.decode()) continue except TypeError: logger.exception("covid data analysis TypeError, data: " + full_message.decode()) continue except: logger.exception("covid data analysis error, data: " + full_message.decode()) continue finally: # Clear to the next transaction data-清空给下一条交易数据 full_message = TryteString.from_unicode('') return resultMsgs
def test_random_no_length(self): """ Trying to create a random TryteString without specifying length. """ with self.assertRaises(TypeError): trytes = TryteString.random()
# All other requests go to light wallet node. RoutingWrapper('http://service.iotasupport.com:14265').add_route('attachToTangle', 'http://localhost:14265'), # Seed used for cryptographic functions. seed=b'SEED9GOES9HERE' ) # Example of sending a transfer using the adapter. bundle = api.send_transfer( depth=100, transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address( # b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' # b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' ), # Amount of IOTA to transfer. # This value may be zero. value=1, # Optional tag to attach to the transfer. tag=Tag(b'ADAPT'), # Optional message to include with the transfer. message=TryteString.from_string('Hello!'), ), ], )
def test_add_transaction_long_message(self): """ Adding a transaction to a bundle, with a message so long that it has to be split into multiple transactions. """ # noinspection SpellCheckingInspection address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999N9GIUF' b'HCFIUGLBSCKELC9IYENFPHCEWHIDCHCGGEH9OFZBN' ) tag = Tag.from_string('H2G2') self.bundle.add_transaction(ProposedTransaction( address = address, tag = tag, message = TryteString.from_string( ''' "Good morning," said Deep Thought at last. "Er... Good morning, O Deep Thought," said Loonquawl nervously. "Do you have... er, that is..." "... an answer for you?" interrupted Deep Thought majestically. "Yes. I have." The two men shivered with expectancy. Their waiting had not been in vain. "There really is one?" breathed Phouchg. "There really is one," confirmed Deep Thought. "To Everything? To the great Question of Life, the Universe and Everything?" "Yes." Both of the men had been trained for this moment; their lives had been a preparation for it; they had been selected at birth as those who would witness the answer; but even so they found themselves gasping and squirming like excited children. "And you're ready to give it to us?" urged Loonquawl. "I am." "Now?" "Now," said Deep Thought. They both licked their dry lips. "Though I don't think," added Deep Thought, "that you're going to like it." "Doesn't matter," said Phouchg. "We must know it! Now!" "Now?" enquired Deep Thought. "Yes! Now!" "All right," said the computer and settled into silence again. The two men fidgeted. The tension was unbearable. "You're really not going to like it," observed Deep Thought. "Tell us!" "All right," said Deep Thought. "The Answer to the Great Question..." "Yes?" "Of Life, the Universe and Everything..." said Deep Thought. "Yes??" "Is..." "Yes?!" "Forty-two," said Deep Thought, with infinite majesty and calm. ''' ), # Now you know.... # Eh, who am I kidding? You probably knew before I did (: value = 42, )) # Because the message is too long to fit into a single fragment, # the transaction is split into two parts. self.assertEqual(len(self.bundle), 2) txn1 = self.bundle[0] self.assertEqual(txn1.address, address) self.assertEqual(txn1.tag, tag) self.assertEqual(txn1.value, 42) txn2 = self.bundle[1] self.assertEqual(txn2.address, address) self.assertEqual(txn2.tag, tag) # Supplementary transactions are assigned zero IOTA value. self.assertEqual(txn2.value, 0)
# We found all transactions on this address, now we need to put all hashes # in a iterable to send it to the get_trytes function hashes = [] for txhash in transactions['hashes']: hashes.append(txhash) # Get Trytes accepts multiple Transaction Hashes trytes = api.get_trytes(hashes)['trytes'] # We need to get all trytes from all messages and put them in the right order # We do this by looking at the index of the transaction parts = [] for trytestring in trytes: tx = Transaction.from_tryte_string(trytestring) parts.append((tx.current_index, tx.signature_message_fragment)) parts.sort(key=lambda x: x[0]) # All that's left is to concatenate and wrap the parts in a TryteString object full_message = TryteString.from_unicode('') for index, part in parts: full_message += part pprint.pprint(json.loads(full_message.decode()))
def JsontoTrytes(file): data = open(file).read() dataString = json.dumps(data) return TryteString.from_unicode(dataString)
def to_tryte_from_picture_trace(picture): enc_image = img_encode_trace(picture) tryte = TryteString.from_bytes(zlib.compress(enc_image)) return tryte
# want, but to keep this example focused, we will only include a # single spend transaction. transfers = [ ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999NDGYBC' b'QZJFGGWZ9GBQFKDOLWMVILARZRHJMSYFZETZTHTZR', ), value = 42, # If you'd like, you may include an optional tag and/or # message. tag = Tag(b'KITTEHS'), message = TryteString.from_string('thanx fur cheezburgers'), ), ], # Specify our multisig address as the input for the spend # transaction(s). # Note that PyOTA currently only allows one multisig input per # bundle (although the protocol does not impose a limit). multisig_input = multisig_address, # If there will be change from this transaction, you MUST specify # the change address! Unlike regular transfers, multisig transfers # will NOT automatically generate a change address; that wouldn't # be fair to the other participants! change_address = None, )
def test_random_wrong_length(self): """ Generating random Trytestring with negative length. """ with self.assertRaises(TypeError): trytes = TryteString.random(length=-5)
''' This example creates a simple transaction with a custom message/tag There is no value attached to this transaction. ''' from iota import Iota from iota import ProposedTransaction from iota import Address from iota import Tag from iota import TryteString # Note that we don't need a seed to send 0 value transactions since these # transactions are not signed, we can publish to any address api = Iota('https://nodes.devnet.iota.org:443') address = 'TOKLOARHKXQCVPPVVIPIJGLUTLTKFHYGMBBLOXJFYGSARLOTYFFSDZNYCOBOCNPGRMJWZCQBNOROUCE9G' tx = ProposedTransaction(address=Address(address), message=TryteString.from_unicode('You did it!'), tag=Tag('HELLOWORLD'), value=0) tx = api.prepare_transfer(transfers=[tx]) result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9) print('Transaction sent to the tangle!') print('https://devnet.thetangle.org/address/%s' % address)
def get_tags(raw_tag): tryte_tag = TryteString(raw_tag[:27]) tryte_tag += '9' * (27 - len(tryte_tag)) return Tag(tryte_tag)
from iota.multisig.types import MultisigAddress import time """ step1 """ bundle_trans = Transaction( hash_= "AVPVVUUNZDTOHNZWIJVNSVQVOWXFGM9SKJSWAPGWNJCNDFPKSTQETASWTROWCSSTFLRFVRYFTYBD99999", # type: Optional[TransactionHash] signature_message_fragment="", # type: Optional[Fragment] address= "FJKKSHBZTAKQNDTIKJYCZBOZDGSZANCZSWCNWUOCZXFADNOQSYAHEJPXRLOVPNOQFQXXGEGVDGICLMOXX", # type: Address value=5, # type: int timestamp=1574903736, # type: int current_index=0, # type: Optional[int] last_index=3, # type: Optional[int] bundle_hash=TryteString.random(81), trunk_transaction_hash= "ZQLLKWWTPNXXKYHWXRIQZKRG9MLW9DHFVXHPGFYACGOUGPWENMEC9ZOWRUORUWEFBEREGNVPNRHXZ9999", # type: Optional[TransactionHash] branch_transaction_hash= "DQEUSNVVGKZUMYXKDUIEDYHCDVVAXGWU9RZUGOGFCFSTDVJEIWIETEGLKUIEKMKKFOKHVGUAELCMWE999", # type: Optional[TransactionHash] tag="QA9999999999999999999999999", # type: Optional[Tag] attachment_timestamp=1574903776620, # type: Optional[int] attachment_timestamp_lower_bound=0, # type: Optional[int] attachment_timestamp_upper_bound=3812798742493, # type: Optional[int] nonce="LSJDSJRHNOHMWNRNJFHEORVHMXY", # type: Optional[Nonce] legacy_tag=None # type: Optional[Tag] ) bundle_trans_2 = Transaction( hash_= "ZQLLKWWTPNXXKYHWXRIQZKRG9MLW9DHFVXHPGFYACGOUGPWENMEC9ZOWRUORUWEFBEREGNVPNRHXZ9999", # type: Optional[TransactionHash] signature_message_fragment="", # type: Optional[Fragment]
'YCXCVQDFGWUKPUABPYNMVPAQUGUHYYLMWZQWRUIDIXGTDAOJKOUGRWDJUUOWGOHMVYLTZHGEZCZHBTMT9RM9XGRJUW' ] }] for account in accounts: # fetch seed seed = account['seed'] fund = account['fund'] addrs = account['addresses'] # log print '[%s] Start' % (seed) # setup iota client api = Iota('http://localhost:14265', seed) # attach each address for address in addrs: # prepare trx trx = ProposedTransaction(address=Address(address), message=TryteString.from_string( "MSG%s%s" % (seed[:5], address[:5])), tag=Tag("TAG%s%s" % (seed[:5], address[:5])), value=0) # attach api.send_transfer(1, [trx]) # ensure we can get the expected amount of funding for that account now api_fund = api.get_account_data(0)['balance'] if api_fund == fund: print '[%s] Success' % (seed) else: print '[%s] Fail: expected %d IOTA, got %d IOTA' % (seed, fund, api_fund)
def batch_transfer(filename, node_uri, seed, amount_of_seeds=100, amount_per_seed=10000, batch_size=25, depth=3, tag='GIFT', message='', pow_node_uri=None): needed_funds = amount_of_seeds * amount_per_seed print('You are about to spend %s iota spread out over %s addresses.' % (needed_funds, amount_of_seeds)) print('Checking your seeds balance...') if pow_node_uri: router = RoutingWrapper(node_uri) router.add_route('attachToTangle', pow_node_uri) api = Iota(router, seed) else: api = Iota(node_uri, seed) inputs = api.get_inputs() balance = inputs['totalBalance'] if balance < needed_funds: print( "You don't have enough funds available on your SEED, please make sure your seed has at least %si available!" % needed_funds) return print( 'You have enough available to transfer the %si, Generating %d seeds and addresses now...' % (needed_funds, amount_of_seeds)) seedlist = [] for i in range(amount_of_seeds): random_seed = ''.join( [choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ9') for x in range(81)]) gen = AddressGenerator(random_seed) new_addr = gen.get_addresses(0, 1, 2)[0] seedlist.append((random_seed, new_addr)) print('.', sep='', end='', flush=True) print('\n') with open(filename, 'w') as fh: writer = csv.writer(fh) writer.writerow(['Seed', 'Address', 'Iota']) for gseed, gaddr in seedlist: writer.writerow([gseed, gaddr, amount_per_seed]) print('All seeds and addresses are now available in %s!' % filename) amount_of_bundles = (amount_of_seeds // batch_size) + 1 if amount_of_seeds % batch_size == 0: amount_of_bundles -= 1 print( 'We will generate and send %d bundles containing %d transactions per bundle max, this can take a while...' % (amount_of_bundles, batch_size)) from_addr = None for i in range(amount_of_bundles): sliced = seedlist[i * batch_size:(i + 1) * batch_size] print('Starting transfer of bundle %d containing %d seeds...' % (i + 1, len(sliced))) transfers = [] for gseed, gaddr in sliced: transfers.append( ProposedTransaction( address=gaddr, value=amount_per_seed, tag=Tag(tag), message=TryteString.from_string(message), )) bundle = api.send_transfer(depth=depth, transfers=transfers) for tx in bundle['bundle'].transactions: if tx.current_index == tx.last_index: print('Remainder:', tx.current_index, tx.address, tx.value) from_addr = tx.address if amount_per_seed == 0: continue print( 'Waiting for the TX to confirm and the remainder address (%s) to fill...' % tx.address) while True: balances = api.get_balances([tx.address], 100) if balances['balances'][0] > 0: break else: print('...', sep='', end='', flush=True) sleep(5) print('\n') print('Transfer complete.') print('All done!')
def test_as_trits_multiple_trytes(self): """ Converting a multiple-tryte TryteString into a sequence of trit values. """ self.assertListEqual( TryteString(b'ZJVYUGTDRPDYFGFXMK').as_trits(), [ -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, ], )
def test_init_error_int(self): """ Attempting to reset a TryteString from an int. """ with self.assertRaises(TypeError): TryteString(42)
#!/usr/bin/python from iota import Iota from iota import Address, ProposedTransaction, ProposedBundle, Tag, Transaction from iota import TryteString from iota.crypto.signing import KeyGenerator # # Create a new bundle transaction # Send from 42 iota account 2 to account 3 # # Connect to the node api = Iota('http://localhost:14265', "S9YOBZWUIHQFGHQCUOFCKHFR99IJMSZNNHUDXRAGDZKLGEBGPNDWROALSUODRJNMFFQHDVNISRMVMPVNE") # Trx setup output_trx = ProposedTransaction( address = Address("E9LVPMKJIAGCIPVKMUOYTQMSYAUQDUMEYUUCLXRQUWJJ9JXRDXQNGIOUPQVIMIWHFIRXD9QSYOP9KG9BWARSINOJ9W"), message = TryteString.from_string("Sending some money"), tag = Tag("PACIFICSOUND"), value = 42) # Propagate api.send_transfer(1, [output_trx])
def test_get_inclusion_states(self): """ Fetching inclusion states with transactions. """ # noinspection PyUnusedLocal def create_generator(ag, start, step=1): for addy in [self.addy1][start::step]: yield addy # The first address received IOTA. self.adapter.seed_response( 'findTransactions', { 'duration': 42, 'hashes': [ 'TESTVALUEFIVE9DONTUSEINPRODUCTION99999VH' 'YHRHJETGYCAFZGABTEUBWCWAS9WF99UHBHRHLIOFJ', ], }, ) # For this test, we have to generate a real TryteString. transaction_trytes = \ TryteString( b'KMYUMNEUAYODAQSNGWTAERRRHNZBZCOLMVVOBTVWLOFYCJKYMGRAMH9RQ9MTZOSZMH' b'QNZFHFEJEDFQ99HSUNVOTULDJGXEDULS9ZHABVDZODJUMCNWVCPNSCUVKVYWCEXBHW' b'RBZBSWFPQLWZWMUPGQIGAEGOVE9DDXBVCIPKQYCFZFBELTSMVFSIXLPTACTKAFMCTK' b'CPYD9BWDJMLKWAOBDSJNQYAHS9GFIQKZCROLFZJVUEIVXVNBRRLEIWTYVHURUXHSCG' b'DKEIEGPOCXKCYWIBUG9ABYCALYJVFLBNGMS9ARHGTQXBZFLENXCJVKHPVKD9KSAEOL' b'FFVAJCNKLDVHOCDARWUNKARDYMVKFKRSMUTYOUXSBFFYTKRREBDJZTLVUROQFCBXQN' b'SXDDYTZTEBRSXOBMLXHJKSJAVOOVCXATOWNQDWHT9CCUAAJUJKDOQLMAEZACSNFKXZ' b'IGWDQEUEFRZYAOSDNVMSXWYLVDAUXZSHNHAIBEMNPFUGORYUETNJK9UCEMSUJYBBDK' b'BHIPKEINQCGOVYCPKUPJMUCUVZOJSIWYRFMFXYUVSMOUALAQBWIMXBUBXSAETGKJRP' b'AHVAXHQJDMEVSRFYEXUSIEBKMGYCUKFD9JPGUV9AIYUVCRUURKMYUHMVE9OJCYYWTQ' b'WUWFMTBZYFXASHHVCMSWXKBRQFHHQVEQMEULJRWZKLWFFSGGKEHUZZFNDNITSRAUH9' b'PQK9OGLYMVBSHXQLLZHOBBIM9KVUWDLHZRDKQQVLQXGWYXEEVQPDZUO9PVXMALOMRQ' b'VCTHGIZLILSCFKTBRESYZGBZKHXEODNDJZ9GK9ROWYXNGFHZCCBHHZEYEOGWXRGSUD' b'SUZFUAUBXVXZHCUVJSYBWTCYCEDYKZNGWFZYKSQLW9FUYMWDVXKZEWT9SCVMQCODZK' b'DRNKTINTPNOJOLGQJDAJMFWRFSWZJLYZGSTSIDSXLUJBZRZNLEDNBKAUNGTCYUPDRW' b'JOCEBQ9YG9IZLLRMJITISJOTLQMOGXVQIZXHMTJVMMWM9FOIOT9KFZMANEPOEOV9HX' b'JNEGURUKRWDGYNPVGAWMWQVABIJNL9MDXKONEPMYACOZ9BE9UZMAFTKYWPFWIQWAPK' b'GUXQTOQVWYYVZYGQDLBIQDVOZIWGOMGOBAUARICQZVNXD9UVEFBBAJKQBHRHXTBUOW' b'VBFKYQWZWTMMXVKZRIZUBVPQ9XHLJHFHWFZUIZVSNAKBDHDFGJCYQETOMEDTOXIUT9' b'OAJVIHWAGTCNPEZTERMMN9EZEWSJHKQAUMXPBZTNQOEQCVXIMAAYO9NIUFLTCFIMK9' b'9AFAGWJFA9VOFPUDJLRAMORGSUDBLWWKXEDZ9XPQUZSGANGESHKKGGQSGSYDCRLHZD' b'PKA9HKYBKLKKCXYRQQIPXCFETJJDZYPCLUNHGBKEJDRCIHEXKCQQNOV9QFHLGFXOCR' b'HPAFCUTPMY9NOZVQHROYJSCMGRSVMOBWADAZNFIAHWGIQUUZBOVODSFAUNRTXSDU9W' b'EIRBXQNRSJXFRAQGHA9DYOQJGLVZUJKAQ9CTUOTT9ZKQOQNNLJDUPDXZJYPRCVLRZT' b'UCZPNBREYCCKHK9FUWGITAJATFPUOFLZDHPNJYUTXFGNYJOBRD9BVHKZENFXIUYDTL' b'CE9JYIIYMXMCXMWTHOLTQFKFHDLVPGMQNITEUXSYLAQULCZOJVBIPYP9M9X9QCNKBX' b'W9DVJEQFFY9KQVMKNVTAHQVRXUKEM9FZOJLHAGEECZBUHOQFZOSPRXKZOCCKAOHMSV' b'QCFG9CWAHKVWNA9QTLYQI9NKOSHWJCNGPJBLEQPUIWJBIOAWKLBXUCERTSL9FVCLYN' b'ADPYTPKJOIEMAQGWBVGSRCZINXEJODUDCT9FHOUMQM9ZHRMBJYSOMPNMEAJGEHICJI' b'PVXRKCYX9RZVT9TDZIMXGZJAIYJRGIVMSOICSUINRBQILMJOUQYXCYNJ9WGGJFHYTU' b'LWOIPUXXFNTIFNOJRZFSQQNAWBQZOLHHLVGHEPWTKKQEVIPVWZUN9ZBICZ9DZZBVII' b'BF9EPHARZJUFJGBQXQFQIBUECAWRSEKYJNYKNSVBCOWTFBZ9NAHFSAMRBPEYGPRGKW' b'WTWACZOAPEOECUO9OTMGABJVAIICIPXGSXACVINSYEQFTRCQPCEJXZCY9XZWVWVJRZ' b'CYEYNFUUBKPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTERYMMBQOPSQIDENXK' b'LKCEYCPVTZQLEEJVYJZV9BWU999999999999999999999999999FFL999999999999' b'9999999999999RJQGVD99999999999A99999999USGBXHGJUEWAUAKNPPRHJXDDMQV' b'YDSYZJSDWFYLOQVFGBOSLE9KHFDLDYHUYTXVSFAFCOCLQUHJXTEIQRNBTLHEGJFGVF' b'DJCE9IKAOCSYHLCLWPVVNWNESKLYAJG9FGGZOFXCEYOTWLVIJUHGY9QCU9FMZJY999' b'9999HYBUYQKKRNAVDPVGYBTVDZ9SVQBLCCVLJTPEQWWOIG9CQZIFQKCROH9YHUCNJT' b'SYPBVZVBNESX999999D9TARGPQTNIYRZURQGVHCAWEDRBJIIEJIUZYENVE9LLJQMXH' b'GSUUYUCPSOWBCXVFDCHHAZUDC9LUODYWO' ) self.adapter.seed_response( 'getTrytes', { 'duration': 99, 'trytes': [binary_type(transaction_trytes)], }, ) transaction = Transaction.from_tryte_string(transaction_trytes) mock_get_bundles = mock.Mock(return_value={ 'bundles': [Bundle([transaction])], }) mock_get_latest_inclusion = mock.Mock(return_value={ 'states': { transaction.hash: True, }, }) with mock.patch( 'iota.crypto.addresses.AddressGenerator.create_iterator', create_generator, ): with mock.patch( 'iota.commands.extended.get_bundles.GetBundlesCommand._execute', mock_get_bundles, ): with mock.patch( 'iota.commands.extended.get_latest_inclusion.GetLatestInclusionCommand._execute', mock_get_latest_inclusion, ): response = self.command( seed=Seed.random(), inclusionStates=True, # To keep the test focused, only retrieve a single # transaction. start=0, stop=1, ) bundle = response['bundles'][0] # type: Bundle self.assertTrue(bundle[0].is_confirmed)
def tryte_hash(msg: str): digest = SHA256.new() digest.update(msg.encode()) hash = digest.hexdigest() tryte_hash = TryteString.from_unicode(hash)[0:81] return tryte_hash.__str__()
from iota import ( __version__, Address, Iota, ProposedTransaction, Tag, TryteString, ) from six import text_type api = Iota('http://localhost:14265') txn_2 =\ ProposedTransaction( address = Address( b'FJHSSHBZTAKQNDTIKJYCZBOZDGSZANCZSWCNWUOCZXFADNOQSYAHEJPXRLOVPNOQFQXXGEGVDGICLMOXX' ), message = TryteString.from_unicode('thx fur cheezburgers'), tag = Tag(b'KITTEHS'), value = 0, ) c = api.prepare_transfer([txn_2])["trytes"] K = api.send_trytes(depth=3, trytes=c, min_weight_magnitude=9) print('Transfer complete.') print(c) print('\n') print(K["trytes"])
from multiprocessing import Process from iota import Iota, ProposedTransaction, Address, Tag, TryteString import sys import json with open('config.json', 'r') as f: data = json.load(f) url = data['url'] # returns JSON object as a dictionary api = Iota(url, testnet=True) address = 'ZLGVEQ9JUZZWCZXLWVNTHBDX9G9KZTJP9VEERIIFHY9SIQKYBVAHIMLHXPQVE9IXFDDXNHQINXJDRPFDXNYVAPLZAW' message = TryteString.from_unicode('Hello world') tx = ProposedTransaction(address=Address(address), message=message, value=0) def request(num=10): for i in range(num): result = api.send_transfer(transfers=[tx]) print(result['bundle'].tail_transaction.hash) if __name__ == "__main__": # confirms that the code is under main function numproc = 1 numtx = 10 if len(sys.argv) == 3: numproc = int(sys.argv[1]) numtx = int(sys.argv[2]) procs = []
def Bundle_Generation(Recepient, ToSend): text_transfer = TryteString.from_string(str(ToSend)) txn_2 = ProposedTransaction(address=Address(Recepient), message=text_transfer, value=0) bundle.add_transaction(txn_2)
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)
from iota import Address, Iota, TryteString, ProposedTransaction from datetime import datetime SEED = b"THISISASEED9999999999999999999999999999999999999999999999999999999999999999999999999999999" api = Iota("https://durian.iotasalad.org:14265", seed=SEED) message = TryteString.from_string( f"Hi PyDATA Hamburg. It's now {datetime.now()}.") receiver = Address( b"ANY9VALID9IOTA9ADDRESS99999999999999999999999999999999999999999999999999999999999999999999" ) tx = ProposedTransaction(address=receiver, value=0, message=message) api.send_transfer(depth=3, transfers=[tx])