def test_get_bundle(self): key = iota.BundleHash( b'9ZMDWNXOJUEQQGBFHFPLIXLFBVFP9QIEJQGCD9B9NOAWBHHTCUDECJ9LSDUVP9YBIZGAKHANXBYQTADEZ' ) value = list(self.provider.get(key, 'bundle')) expect = [ TransactionHash( b'9KTTGBWZWKMGY9OTVFCRKUJTMOSRPNDDYKSWJENSH9MBQU9VKLVCWQPPULJHAYYM9JEMTYDTNTI9Z9999' ), TransactionHash( b'HDLRDWIYLHDEOXEMCIVQOOLOGFEBUDHTRRDRLLDIYQUFPSNCUYRQBRUPB9DWLQWCBYVXTBFYFPYGZ9999' ), TransactionHash( b'INLMRLGUURIAVIKCBUCBNEALFLVHFRGWPKUBBEFKOMFRROCSDGXSTWXRBHOXERJKDCURA9LJUHIN99999' ) ] self.assertEqual(Counter(value), Counter(expect)) # Bad self.assertFalse( list( self.provider.get( iota.TryteString('9' * (iota.Hash.LEN - 1) + 'A'), 'bundle'))) self.assertFalse( list(self.provider.get(iota.BundleHash('FOOBAR'), 'bundle'))) with self.assertRaises(ValueError): self.assertIsNone( self.provider.get(iota.TryteString('FOOBAR'), 'bundle')) with self.assertRaises(TypeError): self.provider.get('', 'bundle')
def test_get_approvee(self): key = iota.TransactionHash( b'UNUK99RCIWLUQ9WMUT9MPQSZCHTUMGN9IWOCOXWMNPICCCQKLLNIIE9UIFGKZLHRI9QAOEQXQJLL99999' ) value = list(self.provider.get(key, 'approvee')) expect = [ TransactionHash( b'YUPJOZMOSVIEQZXSVTLSYMIGMLFGDBPSZUTRAML9MIQNCLCMPOGFRAYLSFJUDBJBFDGESTIAFGZR99999' ), TransactionHash( b'ELIWEYAYXYEFOWBHJMELTKVERQWTJF9RXRLISNNQQVWGS9EMYYBVWRJYVJUYAPBGDQNYQEZOPBXWA9999' ), ] self.assertEqual(Counter(value), Counter(expect)) # Bad self.assertFalse( list( self.provider.get( iota.TryteString('9' * (iota.Hash.LEN - 1) + 'A'), 'approvee'))) self.assertFalse( list(self.provider.get(iota.TransactionHash('FOOBAR'), 'approvee'))) with self.assertRaises(ValueError): self.assertIsNone( self.provider.get(iota.TryteString('FOOBAR'), 'approvee')) with self.assertRaises(TypeError): self.provider.get('', 'approvee')
def test_get_state_diff(self): key, value = self.provider.latest('state_diff') self.assertIsInstance(key, iota.TransactionHash) self.assertIsInstance(value, types.GeneratorType) # Bad self.assertFalse(list(self.provider.get(iota.TryteString('9' * (iota.Hash.LEN - 1) + 'A'), 'state_diff'))) self.assertFalse(list(self.provider.get(iota.TransactionHash('FOOBAR'), 'state_diff'))) with self.assertRaises(ValueError): self.assertIsNone(self.provider.get(iota.TryteString('FOOBAR'), 'state_diff')) with self.assertRaises(TypeError): self.provider.get('', 'state_diff')
def test_get_address(self): key = iota.Address(b'9TPHVCFLAZTZSDUWFBLCJOZICJKKPVDMAASWJZNFFBKRDDTEOUJHR9JVGTJNI9IYNVISZVXARWJFKUZWC') value = list(self.provider.get(key, 'address')) self.assertGreaterEqual(len(value), 84) self.assertIsInstance(value[0], iota.TransactionHash) # Bad self.assertFalse(list(self.provider.get(iota.TryteString('9' * (iota.Hash.LEN - 1) + 'A'), 'address'))) self.assertFalse(list(self.provider.get(iota.Address('FOOBAR'), 'address'))) with self.assertRaises(ValueError): self.assertIsNone(self.provider.get(iota.TryteString('FOOBAR'), 'address')) with self.assertRaises(TypeError): self.provider.get('', 'address')
def get_messages_from_transactions(txns): data = [] txn_count = 0 bundle_count = 0 for txn in txns: message = txn.signature_message_fragment message = iota.TryteString(message) try: message = message.decode() message = json.loads(message) data.append(message) txn_count += 1 except iota.TrytesDecodeError: print( "[-] Trytes Decode Error. Trying to get message from the bundle" ) hash = txn.hash messages = get_message_from_bundle(hash) bundle_count += len(messages) print("[+] Got {} message(s) from bundle".format(len(messages))) data += messages print("Retrived data from: {} txns, {} bundles".format( txn_count, bundle_count)) return data
def trytes_encode(): trytes_bytes = 'YZJEATEQ9JKLZ' trytes = iota.TryteString(trytes_bytes) pprint(trytes) trits = trytes.as_trits() print(trits)
async def async_connect(self, session, url): import iota async with session.ws_connect(url) as ws: for listener in self._listener_states.values(): await self.subscribe(ws, listener) while True: listener_id, listener, bundle_hash, data = await self.get_next_message( ws) payload_json = data['payload'] payload_json = iota.TryteString(payload_json).encode() payload = json.loads(payload_json) self._hass.bus.fire( EVENT_ACTION_TRIGGERED, { ATTR_ROOT: listener[ATTR_ROOT], ATTR_BUNDLE: bundle_hash, ATTR_PAYLOAD: payload }) await self.unsubscribe(ws, listener_id) listener[ATTR_NEXT_ROOT] = data['next_root'] await self.subscribe(ws, listener) # update iota_mam_listeners.yaml with open(self._hass.config.path(YAML_LISTENER_STATES), 'w') as out: out.write(dump(self._listener_states))
def init_from_snapshot(self, verify): self.snapshot_data = resource_string('iotapy.resources', 'Snapshot.txt') self.snapshot_sig = resource_string('iotapy.resources', 'Snapshot.sig').splitlines() self.state = {} # Init snapshot curl = iota.crypto.kerl.Kerl() for line in self.snapshot_data.splitlines(): trits = iota.TryteString.from_bytes(line).as_trits() if verify: curl.absorb(trits) key, value = line.split(b';') self.state[iota.Hash(key)] = int(value) if not self.is_consistent(): raise ValueError('Snapshot total supply or address value is bad') # Check snapshot signature if not verify: return trits = [] curl.squeeze(trits) mode = iota.crypto.Curl bundle_hash = iota.BundleHash.from_trits(trits) bundles = iota.crypto.signing.normalize(bundle_hash) digests = [] for i, bundle in enumerate(bundles): digests.extend( ISS.digest(mode, bundle, iota.TryteString(self.snapshot_sig[i]))) root = ISS.get_merkle_root( mode, ISS.address(mode, digests), iota.TryteString(self.snapshot_sig[-1]).as_trits(), 0, self.SNAPSHOT_INDEX, self.SNAPSHOT_PUBKEY_DEPTH) if root != iota.TryteString(self.SNAPSHOT_PUBKEY).as_trits(): raise ValueError('Snapshot signature failed')
def curl_hash(*keys): import iota key = [] curl = iota.crypto.Curl() for k in keys: curl.absorb(iota.TryteString(k).as_trits()) curl.squeeze(key) return iota.TryteString.from_trits(key)
def attach_message(self, address, payload): import iota trytes = self._api.prepare_transfer(transfers=[ iota.ProposedTransaction(address=iota.Address(address), message=iota.TryteString(payload), value=0) ]) self._api.send_trytes(trytes["trytes"], depth=6, min_weight_magnitude=14)
def add_tx_to_tangle(self, tx): self.graph.add_node(tx.hash, tx=tx, confirmed=False, trunk=tx.trunk_transaction_hash) self.graph.add_edge(tx.hash, tx.branch_transaction_hash) self.graph.add_edge(tx.hash, tx.trunk_transaction_hash) timestamp = iota.int_from_trits( iota.TryteString(tx.timestamp).as_trits()) self.graph.node[tx.hash]['timestamp'] = timestamp if tx.address == self.COOR: self.graph.node[tx.hash]['is_milestone'] = True index = iota.int_from_trits(iota.TryteString(tx.tag).as_trits()) self.graph.node[tx.hash]['index'] = index self.latest_milestone = tx.hash self.milestones[tx.hash] = index if self.latest_milestone_index < index: self.latest_milestone_index = index self.milestone_count += 1
def main(): if len(sys.argv) < 2: print "Usage: echocatcher-client.py <slack-username/contact-info> [zmq-port (default 5556)]" exit(-1) #fill in contact info ping_msg = sys.argv[1] echo_catcher = "ECHOCATCHER" port = "5556" if len(sys.argv) > 2: port = sys.argv[2] int(port) # Socket to talk to server context = zmq.Context() socketZ = context.socket(zmq.SUB) socketZ.connect("tcp://localhost:%s" % port) # Subscribe to topic topicfilter = "tx" socketZ.setsockopt(zmq.SUBSCRIBE, topicfilter) # Create a UDP socket to send ping sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Process updates total_value = 0 while True: string = socketZ.recv() topic, hash, address, value, tag, timestamp, currentIndex, lastIndex, bundle, trunk, branch = string.split( ) if echo_catcher in tag: print "found an ECHOCATCHER message:" print "Sending ping to:" message = iota.TryteString(address).as_string() print message try: message = message.replace('udp://', '') ip, port = message.split(':') server_address = (ip, int(port)) sent = sock.sendto( ping_msg + ":" + str(port) + ":" + '{:.2f}'.format(time.time() - int(timestamp)), server_address) except: print "error parsing:", message
def test_get_tag(self): key = iota.Tag(b'EXAMPLEPYTHONLIB') value = list(self.provider.get(key, 'tag')) expect = [ TransactionHash(b'GTXDTJVUTVSNHYFPJUOWFKTGQTCMNKZPJDJXSWVQWTXYRDZAVZTX9KFBRIMRQEQLMCMVAUKMZWMHA9999'), TransactionHash(b'PZYRMRVTSPQXNEQIQEBAGINMDAKOHPOLNH9LR9DTFWMWFQICXL9BJCWBUPMKZERKYKBDRIBYEJYH99999'), TransactionHash(b'UNUK99RCIWLUQ9WMUT9MPQSZCHTUMGN9IWOCOXWMNPICCCQKLLNIIE9UIFGKZLHRI9QAOEQXQJLL99999') ] for v in value: self.assertIn(v, expect) # Bad with self.assertRaises(TypeError): self.assertIsNone(self.provider.get(iota.TryteString('FOOBAR'), 'tag')) with self.assertRaises(TypeError): self.provider.get('', 'tag')
def send_transfer(tag, message, address, values, dict_tips): ## Set output transaction print("Start to sransfer ... ") propose_bundle = iota.ProposedBundle() print("Setting output transaction ...") txn_output = iota.ProposedTransaction(address=iota.Address(address), value=values, tag=iota.Tag(tag), message=iota.TryteString(message)) propose_bundle.add_transaction(txn_output) # Get input address if int(values) > 0: print "DEBUG values = " + 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 = 1 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(gen_a_address()['addresses'][0]) propose_bundle.send_unspent_inputs_to(unspent) # This will get the bundle hash print("Bundle finalize ...") propose_bundle.finalize() ## 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['branchTransaction'] branch_hash = dict_tips['trunkTransaction'] # Do PoW (attach to tangle) for tx_tryte in trytes: # TODO: Timestamp # timestamp = None # timestamp_lower_bound = None # timestamp_upper_bound = None # 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 = '' with tempfile.TemporaryFile() as tempf: proc = subprocess.Popen( ['python', 'tx_search_nonce.py', str(tx_tryte), str(14)], stdout=tempf) proc.wait() tempf.seek(0) nonce = tempf.read().rstrip() tx_tryte = insert_to_trytes(2646, 2673, str(nonce), tx_tryte) print "Prepare to broadcast ..." try: api.broadcast_transactions([tx_tryte[0:2673]]) except Exception as e: print "Error: " + str(e.context) return propose_bundle.hash
def spam(api, txid, trans=None, max_time=None): if txid is not None: try: tx_trytes = api.get_trytes([ iota.TransactionHash(iota.TryteString(txid.encode('ascii'))) ])['trytes'][0] except: logger.error(traceback.format_exc()) return input_tx = iota.Transaction.from_tryte_string(tx_trytes) else: input_tx = trans start_time = time.time() logger.info('start promoting tx (%smin, %smi): %s (%s)', round((start_time - input_tx.timestamp) / 60), round(input_tx.value / 1000**2), input_tx.hash, input_tx.bundle_hash) count = 0 max_count = 7 sleeping = 0 while True: if is_confirmed(api, input_tx.bundle_hash): logger.info('bundle confirmed: %s', input_tx.bundle_hash) sumlogger.info('Success: %smin - %smi: %s', round((time.time() - start_time) / 60), round(input_tx.value / 1000**2), input_tx.bundle_hash) return try: tx_hashes = api.find_transactions([input_tx.bundle_hash])['hashes'] except: logger.warning(traceback.format_exc()) time.sleep(60) continue if len(tx_hashes) < 3: logger.warning('what is this bundle? only %s tx', len(tx_hashes)) bad_bundles.append(input_tx.bundle_hash) return logger.info('found %s tx in bundle. trying to promote/reattach', len(tx_hashes)) tx_trytes = [] chunks = [ tx_hashes[x:x + 1000] for x in range(0, len(tx_hashes), 1000) ] for chunk in chunks: try: tx_trytes += (api.get_trytes(chunk)['trytes']) except: logger.error(traceback.format_exc()) continue txs = [] for x in tx_trytes: txs.append(iota.Transaction.from_tryte_string(x)) tails = list(filter(lambda x: x.is_tail, txs)) tails = sorted(tails, key=lambda x: x.attachment_timestamp / 1000, reverse=True)[:min(len(tails), 10)] for tx in tails: if count < max_count: promote(api, tx) else: if reattach(api, tx): if not sleeping: sleeping = random.randint(1, 3) break if count == max_count: count = 0 else: count += 1 logger.info('run finished. %s more runs until reattach', max_count - count) while sleeping > 0: logger.info('%s min wait...', sleeping) time.sleep(60) sleeping -= 1 if max_time and ((time.time() - start_time) > max_time): logger.warning('Did take too long (%s).. Skipping', round((time.time() - start_time) / 60)) sumlogger.info('Timeout: %smin - %smi: %s', round((time.time() - start_time) / 60), round(input_tx.value / 1000**2), input_tx.bundle_hash) return
r = requests.post("http://140.116.247.117:14265", data=json.dumps(f), headers=headers) return r.text SEED = 'BXOM9LUNLPSEXBRJV9UUNLHSUHABEOGHQOGNBNBUEYSGOFZOEPYKEYRSFTXBOEJLUODUQXXGQ9NWQBSGH' api = Iota('http://140.116.247.117:14265', b'BXOM9LUNLPSEXBRJV9UUNLHSUHABEOGHQOGNBNBUEYSGOFZOEPYKEYRSFTXBOEJLUODUQXXGQ9NWQBSGH') gna_result = api.get_new_addresses(count=2) bundle = ProposedBundle() tag = iota.Tag('TESTINGPYTHON') pt = iota.ProposedTransaction( address=iota.Address('9TPHVCFLAZTZSDUWFBLCJOZICJKKPVDMAASWJZNFFBKRDDTEOUJHR9JVGTJNI9IYNVISZVXARWJFKUZWC'), value=0, tag=tag, message=iota.TryteString('HELLO') ) bundle.add_transaction(pt) addy = gna_result["addresses"][0] addy.balance = 0 addy.key_index = 0 bundle.add_inputs([ addy ]) bundle.send_unspent_inputs_to( gna_result["addresses"][0] )
def H(in_trytes): out = H_Kerl(iota.TryteString(in_trytes).as_trits()) return str(iota.TryteString.from_trits(out))
in_trits = [long(random.randrange(-1,2)) for j in range(243)] in_trits[242] = 0 in_big = Kerl.convertTritsToBigint(in_trits) bytes = Kerl.convertBigintToBytes(in_big) out_big = Kerl.convertBytesToBigInt(bytes) out_trits = Kerl.convertBigintToTrits(out_big) assert in_trits==out_trits, "{}\n{} != \nAssertionError: {}\n{}\n{}".format(i,in_trits,out_trits,in_big,out_big) ############################ #Test Kerl: ############################ #kerlOneAbsorb TS = "EMIDYNHBWMBCXVDEFOFWINXTERALUKYYPPHKP9JJFGJEIUY9MUDVNFZHMMWZUYUSWAIOWEVTHNWMHANBH" in_value = iota.TryteString(TS).as_trits() out_value = H_Kerl(in_value) out_value_trytes = iota.TryteString.from_trits(out_value) expected = "EJEAOOZYSAWFPZQESYDHZCGYNSTWXUMVJOVDWUNZJXDGWCLUFGIMZRMGCAZGKNPLBRLGUNYWKLJTYEAQX" assert str(out_value_trytes)==expected #kerlMultiSqeeze TS = "9MIDYNHBWMBCXVDEFOFWINXTERALUKYYPPHKP9JJFGJEIUY9MUDVNFZHMMWZUYUSWAIOWEVTHNWMHANBH" in_value = iota.TryteString(TS).as_trits() k = Kerl() k.absorb(in_value) out_value = [] k.squeeze(out_value) out_value_trytes = iota.TryteString.from_trits(out_value) expected = "G9JYBOMPUXHYHKSNRNMMSSZCSHOFYOYNZRSZMAAYWDYEIMVVOGKPJBVBM9TDPULSFUNMTVXRKFIDOHUXX" assert str(out_value_trytes)==expected
def get_random_trytes(self): return iota.TryteString(''.join( [random.choice(ALPHABETS) for _ in range(self.TRYTE_LENGTH)]))
def get_random_trytes(seed=None): if seed: random.seed(seed) return iota.TryteString(''.join( [random.choice(ALPHABETS) for _ in range(TRYTE_LENGTH)]))