コード例 #1
0
def getInformation(hash_value, seed=None):
    # 获取IOTA api函数接口
    if seed is None:
        api = Iota(ip, testnet=True)
    else:
        api = Iota(ip, seed=seed, testnet=True)
    # 获取交易捆绑
    bundle = api.get_bundles(hash_value)
    # 读取交易信息
    message = bundle['bundles'][0].tail_transaction.signature_message_fragment
    # 将信息转成json数据格式并返回
    jsonData = json.loads(message.decode())
    return jsonData
コード例 #2
0
def findmessages(TXN_BUNDLE):
    api = Iota('http://node.deviceproof.org:14265')
    dict_txn = api.find_transactions(bundles = [TXN_BUNDLE.rstrip()])

    if len(dict_txn["hashes"]) == 0:
        return ""

    tail_hash = dict_txn['hashes']
    test = str(tail_hash)[19:100]

    bundle = api.get_bundles(test)
    signature_message_fragment = str(bundle["bundles"][0][0].signature_message_fragment)

    ans = TryteString(signature_message_fragment).decode()
    return ans
コード例 #3
0
def findmessages(TXN_BUNDLE):
    #print("hello bundle is : " + str(TXN_BUNDLE))
    api = Iota('http://node.deviceproof.org:14265')
    dict_txn = api.find_transactions(bundles=[TXN_BUNDLE.rstrip()])
    #print("Transaction = ",dict_txn['hashes'])

    tail_hash = dict_txn['hashes']
    test = str(tail_hash)[19:100]
    #print("Transaction hash = ",test)

    bundle = api.get_bundles(test)
    signature_message_fragment = str(
        bundle["bundles"][0][0].signature_message_fragment)

    ans = TryteString(signature_message_fragment).decode()
    return ans
コード例 #4
0
    def test_wireup(self):
        """
        Verify that the command is wired up correctly. (sync)

        The API method indeed calls the appropiate command.
        """
        with patch('iota.commands.extended.get_bundles.GetBundlesCommand.__call__',
                MagicMock(return_value=async_return('You found me!'))
                ) as mocked_command:

            api = Iota(self.adapter)

            # Don't need to call with proper args here.
            response = api.get_bundles('transactions')

            self.assertTrue(mocked_command.called)

            self.assertEqual(
                response,
                'You found me!'
            )
コード例 #5
0
def gen_bundle_info_for_transfer(bundle_idx, label, seed, dst_addr, value):
    # api
    api = Iota('http://localhost:14265', seed)

    # find all transactions for address
    trxs = api.find_transactions(addresses=[dst_addr])['hashes']
    bundle = None

    # try to find the right bundle
    for trx in trxs:
        try:
            trx_bundles = api.get_bundles(trx)['bundles']

            for trx_bundle in trx_bundles:
                try:
                    if trx_bundle.transactions[
                            0].value == value and trx_bundle.transactions[
                                0].address == dst_addr:
                        bundle = trx_bundle
                        break
                except:
                    pass

            if bundle:
                break
        except:
            pass

    # If trx could not be found, raise and stop now
    if not bundle:
        raise BaseException("Could not find bundle for trx %s (%di)" %
                            (dst_addr, value))

    bundle_info = \
"""
//!
//! Bundle %d
//! %s
//!
static const std::string BUNDLE_%d_HASH = "%s";
""" % (bundle_idx, label, bundle_idx, bundle.hash)

    for i in range(0, len(bundle.transactions)):
        trx_idx = i + 1
        trx = bundle.transactions[i]
        bundle_info += \
"""
static const std::string BUNDLE_%d_TRX_%d_HASH                      = "%s";
static const std::string BUNDLE_%s_TRX_%s_ADDRESS                   = "%s";
static const std::string BUNDLE_%d_TRX_%d_ADDRESS_WITHOUT_CHECKSUM  = "%s";
static const std::string BUNDLE_%d_TRX_%d_TRYTES                    = "%s";
static const std::string BUNDLE_%d_TRX_%d_SIGNATURE_FRAGMENT        = "%s";
static const int64_t     BUNDLE_%d_TRX_%d_CURRENT_INDEX             = %d;
static const int64_t     BUNDLE_%d_TRX_%d_LAST_INDEX                = %d;
static const std::string BUNDLE_%d_TRX_%d_NONCE                     = "%s";
static const std::string BUNDLE_%d_TRX_%d_TAG                       = "%s";
static const int64_t     BUNDLE_%d_TRX_%d_TS                        = %d;
static const std::string BUNDLE_%d_TRX_%d_TRUNK                     = "%s";
static const std::string BUNDLE_%d_TRX_%d_BRANCH                    = "%s";
static const int64_t     BUNDLE_%d_TRX_%d_VALUE                     = %d;
""" % (
        bundle_idx, trx_idx, trx.hash,
        bundle_idx, trx_idx, trx.address.with_valid_checksum(),
        bundle_idx, trx_idx, trx.address,
        bundle_idx, trx_idx, trx.as_tryte_string(),
        bundle_idx, trx_idx, trx.signature_message_fragment,
        bundle_idx, trx_idx, trx.current_index,
        bundle_idx, trx_idx, trx.last_index,
        bundle_idx, trx_idx, trx.nonce,
        bundle_idx, trx_idx, trx.tag,
        bundle_idx, trx_idx, trx.timestamp,
        bundle_idx, trx_idx, trx.trunk_transaction_hash,
        bundle_idx, trx_idx, trx.branch_transaction_hash,
        bundle_idx, trx_idx, trx.value
        )

    return bundle_info
コード例 #6
0
class MyIOTA:
    def __init__(self, node, seed):
        self.node = node
        self.seed = seed
        self.api = False
        self._update = False
        self.transfers = []
        self._debug = False

        self.wallet = self.get_filename()

        self.addr_dict = {}

        self.min_weight_magnitude = 14

        self.api = Iota(self.node, self.seed)

        self.USED = True
        self.NOT_USED = False

    def Address(self, addr_string):
        return Address(addr_string)

    def get_addr_dict(self):
        return self.addr_dict

    def set_addr_dict(self, addr, value, used):
        self.addr_dict[addr] = (value, used)

    def s_addr(self, addr, n=3):
        s_addr = str(addr)
        l = len(s_addr)

        return s_addr[:n] + '...' + s_addr[l - n:]

    def get_filename(self):
        h = hashlib.sha256()
        h.update(self.seed)
        filename = h.hexdigest()[:20] + '.txt'

        return filename

    def init_wallet(self):
        filename = self.wallet

        # file exists
        if os.path.isfile(filename):
            filefd = open(filename, 'r+')

            self.debug(
                'Wallet file {0} exists. Opening it...'.format(filename))

            for line in filefd:
                line = line.rstrip('\n')

                addr, index, value, used = line.split(',')

                self.debug('reading from file: {0},{1},{2}'.format(
                    self.s_addr(addr, 3), value, used))

                used = used == 'True'

                addr = Address(addr, key_index=int(index), security_level=2)
                self.addr_dict[addr] = (int(index), int(value), used)

            filefd.close()
        else:
            filefd = open(filename, 'w')
            self.debug('Wallet file {0} doesnt exist. Creating it...'.format(
                filename))
            filefd.close()

    def is_empty_wallet(self):
        return len(self.addr_dict) == 0

    def get_fund_inputs(self, inputs):
        total_fund = 0

        for addr in inputs:
            index, value, used = self.addr_dict[addr]

            # TODO: abs. is this right?
            total_fund += abs(value)

        return total_fund

    def write_updates(self):
        filefd = open(self.wallet, 'w')

        self.debug('Writing (updating) wallet...')

        for addr in self.addr_dict:
            v = self.addr_dict[addr]

            line = 'Writing: {0},{1},{2},{3}\n'.format(self.s_addr(addr), v[0],
                                                       v[1], v[2])
            self.debug(line)

            filefd.write('{0},{1},{2},{3}\n'.format(addr, v[0], v[1], v[2]))

        filefd.close()

    def update_wallet(self, input_fund, inputs, change_addr):
        copy_dict = self.addr_dict.copy()

        for addr in inputs:
            v = self.addr_dict[addr]
            #self.debug('Spending {0} from input {1}'.format(self.s_addr(addr), v))

            # Negative fund and used address
            new_value = (v[0], -v[1], not v[2])

            self.debug('Updating input address {0} to: {1}'.format(
                self.s_addr(addr), new_value))

            self.addr_dict[addr] = new_value

        change_fund = self.get_fund_inputs(inputs) - input_fund

        v = self.addr_dict[change_addr]
        change_value = (v[0], change_fund, self.NOT_USED)

        self.debug('Updating change address {0} to: {1}'.format(
            self.s_addr(change_addr), change_value))

        self.addr_dict[change_addr] = change_value

        self.write_updates()

    def enable_debug(self):
        self._debug = True

    def debug(self, msg):
        if self._debug:
            print '[+] Debug: ', msg

    def get_node_info(self):
        return self.api.get_node_info()

    def make_addr_list(self, start_index, n):
        self.iota_assert(start_index >= 0 and n > 0,
                         'must be positive numbers. N should be at least 1.')

        result = self.api.get_new_addresses(index=start_index, count=n)
        addresses = result['addresses']

        for i in range(n):
            addr = addresses[i]
            value = self.get_addr_balance(addr)

            # TODO: Why always False
            self.addr_dict[addr] = (i, value, False)

        self.write_updates()

    def get_addr_balance(self, addr):
        # TODO: addr is a list with just one element
        result = self.api.get_balances([addr])

        balance = result['balances']

        return (balance[0])

    def prepare_transfer(self,
                         transfer_value,
                         dest_addr,
                         tag='DEFAULT',
                         msg='DEFAULT'):
        # TODO: verify address (checksum)
        # TODO: use mi, gi, etc

        msg = TryteString.from_string(msg)

        txn = ProposedTransaction(
            address=Address(dest_addr),
            message=msg,
            tag=Tag(tag),
            value=transfer_value,
        )

        return txn

    def find_transactions(self):
        addr_list = []
        for e in self.addr_dict.items():
            addr = e[0]

            addr_list.append(addr)

        return self.api.findTransactions(addresses=addr_list)['hashes']

    def get_bundle(self, trans):
        return self.api.getBundles(transaction=trans)

    def get_latest_inclusion(self, addrl):
        return self.api.get_latest_inclusion(hashes=addrl)

    def get_total_fund(self):
        total_fund = 0

        for addr in self.addr_dict.items():
            # key and value from dict
            k, v = addr

            index, value, used = v

            #if not used:
            total_fund += value

        return total_fund

    def get_number_of_address(self):
        return len(self.addr_dict)

    def is_all_addr_used(self):
        for addr in self.addr_dict:
            for e in self.addr_dict.items():
                addr, v = e
                index, value, used = v

                if used == False:
                    return True

    def get_more_addr(self, n=10):
        start_index = self.get_number_of_address()

        self.debug('Getting more addresses...please wait...')

        self.make_addr_list(start_index, n)

    def send_transfer(self,
                      input_fund,
                      inputs,
                      outputs,
                      change_addr,
                      savetofile=True):
        # TODO: How to send MANY transactions.
        self.debug('Sending {0} transactions, please wait...'.format(
            len(outputs)))

        self.api.send_transfer(inputs=inputs,
                               transfers=outputs,
                               depth=7,
                               change_address=change_addr,
                               min_weight_magnitude=self.min_weight_magnitude)

        self.debug('Sent.')
        if self.is_all_addr_used():
            # We do an update to wallet file here.
            self.get_more_addr(n=10)

        if savetofile:
            self.update_wallet(input_fund, inputs, change_addr)

    def get_bundles(self, hasht):
        return self.api.get_bundles(hasht)

    def get_trytes(self, hashl):
        return self.api.get_trytes(hashl)['trytes'][0]

    def get_transaction_from_trytes(self, trytes):
        txn = Transaction.from_tryte_string(trytes)

        return txn

    def get_transaction_fields(self, txn):
        #confirmed = str(txn.is_confirmed)
        timestamp = str(txn.timestamp)
        address = str(txn.address)
        value = str(txn.value)
        message = str(txn.signature_message_fragment)
        #message   = str(txn.message)
        tag = str(txn.tag)

        return (timestamp, address, value, tag, message)

    def get_info_transactions(self, transactions_hashes):
        txn_tuples = []

        for h in transactions_hashes:
            trytes = self.get_trytes([h])
            txn = self.get_transaction_from_trytes(trytes)

            # Get confirmed flag
            li_result = self.get_latest_inclusion([bytes(h)])
            confirmed_t = li_result['states'][h]

            (_, addr_t, value_t, tag_t,
             msg_t) = self.get_transaction_fields(txn)

            txn_tuples.append((confirmed_t, addr_t, value_t, tag_t, msg_t))

        return txn_tuples

    def get_any_valid_addr(self):
        #TODO: verify
        #return self.addr_dict.keys()[0]

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if not used:
                return addr

        return None

    def get_inputs(self, fund):
        # TODO: Zero fund
        fund_sum = 0
        addr_list = []
        change_addr = None

        # Zero fund transactions. We return any addr and any change_addr
        if fund == 0:
            # TODO: What if it conflicts with one another?
            addr_list.append(self.get_any_valid_addr())
            change_addr = self.get_any_valid_addr()

            return (addr_list, change_addr)

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if fund_sum < fund:
                #if value > 0 and not used:
                if value > 0 and used == self.NOT_USED:
                    fund_sum += value
                    self.debug(
                        'Found request: {0}. Found address {1} with fund {2}.'.
                        format(fund, self.s_addr(addr), value))
                    addr_list.append(addr)

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if used == self.NOT_USED and addr not in addr_list:
                change_addr = addr

                self.debug('Using {0} as change addr.'.format(
                    self.s_addr(addr)))
                break
        return (addr_list, change_addr)

        #else:
        #    # TODO
        #    self.iota_assert(True, 'No change addr available.')

    def iota_assert(self, condition, msg):
        if not condition:
            print 'Error: ', msg
            sys.exit(-1)
コード例 #7
0
from iota import Iota
from simplecrypt import decrypt
from base64 import b64decode
from getpass import getpass

import json

# Declare an API object
api = Iota('https://nodes.devnet.iota.org:443', testnet=True)

# Prompt user for tail tx hash of the bundle
tail_hash = input('Tail transaction hash of the bundle: ')

print('Looking for bundle on the Tangle...')
# Fetch bundle
bundle = api.get_bundles(tail_hash)['bundles'][0]

print('Extracting data from bundle...')
# Get all messages from the bundle and concatenate them
b64_encrypted_data = "".join(bundle.get_messages())

# Decode from base64
encrypted_data = b64decode(b64_encrypted_data)

# Prompt for passwword
password = getpass('Password to be used for decryption:')

print('Decrypting data...')
# Decrypt data
# decrypt returns 'bytes' in Python 3, decode it into string
json_data = decrypt(password, encrypted_data).decode('utf-8')
コード例 #8
0
from iota import Iota
from simplecrypt import decrypt
from base64 import b64decode
from getpass import getpass

import json

# Declare an API object
api = Iota('https://nodes.devnet.iota.org:443', devnet=True)

# Prompt user for tail tx hash of the bundle
tail_hash = input('Tail transaction hash of the bundle: ')

print('Looking for bundle on the Tangle...')
# Fetch bundle
bundle = api.get_bundles([tail_hash])['bundles'][0]

print('Extracting data from bundle...')
# Get all messages from the bundle and concatenate them
b64_encrypted_data = "".join(bundle.get_messages())

# Decode from base64
encrypted_data = b64decode(b64_encrypted_data)

# Prompt for passwword
password = getpass('Password to be used for decryption:')

print('Decrypting data...')
# Decrypt data
# decrypt returns 'bytes' in Python 3, decode it into string
json_data = decrypt(password, encrypted_data).decode('utf-8')
コード例 #9
0
def detct():
    # for i in range(101):
    if GPIO.input(M_pin):
        motion = 'Someone is closing'
        #print ("Someone is closing!")
        # buzzer(M_pin)
    else:

        GPIO.output(B_pin, GPIO.HIGH)
        motion = 'Nobody Here'
        #print ("Nobody!")
        # time.sleep(2)

    t, h = dt11()

    s = smoke()
    f = flame()

    #data = 'Temp: ' + str(t) + '\xb0 | Humi: ' + str(h)+'% | Gas: ' + s+' | Flame: '+ f +' | Motion: ' + motion
    data = 'Temp: ' + str(t) + '  | Humi: ' + str(h) + '  | Gas: ' + \
        s + '  | Flame: ' + f + '  | Motion: ' + motion
    #data = 'abcd'

    api = Iota('https://nodes.devnet.iota.org:443', testnet=True)

    #address = Address.random(81)
    address = Address(
        'YEQFOMPOTSQXIDGVULITXSXHQOSRLJIUZB9LKTXRHUM9IHYLWYXZTBMLBZRATRFPUVRVRMSYZPDRMWNMQCTGMTRGSZ'
    )

    ######
    ######

    my_data = TryteString.from_unicode(data)

    # Define a zero-value transaction object
    # that sends the message to the address
    tx = ProposedTransaction(address=address, message=my_data, value=0)

    print('Attaching to IOTA')

    result = api.send_transfer(transfers=[tx])
    txn_hash = result['bundle'].tail_transaction.hash

    print('Attached')

    print('Transaction Hash:', txn_hash)
    # time.sleep(.5)

    print('Retriving from IOTA')

    bundle = api.get_bundles(txn_hash)
    message = bundle['bundles'][0].tail_transaction.signature_message_fragment

    output = message.decode()

    print('Message:', output)
    print('https://explorer.iota.org/devnet/address/' + str(address))
    exp = output.split(' ')

    if s == 'Gas Leakage' or f == 'Fire! Fire!!' or motion == 'Someone is closing':
        buzzer(True)
コード例 #10
0
class TangleConnector:
    def __init__(self,
                 url='https://perma.iota.partners:443',
                 seed="TESTSEED9"):
        self.iri_url = url
        self.iota_api = Iota(url, seed)

    def get_node(self) -> Dict:
        """
        Get IRI node info
        """
        try:
            res = self.iota_api.get_node_info()
        except BadApiResponse as e:
            logger.warning("Failed to IRI node info for " + self.iri_url, e)
            res = None
        return res

    def get_tips(self) -> Dict:
        """
        Get all unreferenced transactions
        """
        try:
            res = self.iota_api.get_tips()
        except BadApiResponse as e:
            logger.warning("Failed to get tips", e)
            res = None
        return res

    def get_hashes_from_addr(self, address: Address) -> List[TransactionHash]:
        """
        Get all tx from address
        """
        try:
            response = self.iota_api.find_transactions(addresses=[address])
            hashes = response['hashes']
        except (BadApiResponse, KeyError) as e:
            logger.warning(
                "Failed to get all tx from address " + address.__str__(), e)
            hashes = None
        return hashes

    def get_trytes_from_hashes(
            self, hashes: List[TransactionHash]) -> List[TryteString]:
        """
        Get tryte signature fragments from hashes
        """
        try:
            response = self.iota_api.get_trytes(hashes)
            trytes = [tryte[0:2187] for tryte in response['trytes']]
        except (BadApiResponse, KeyError) as e:
            logger.warning("Failed to get all signature fragments", e)
            trytes = None
        return trytes

    def get_all_trytes_from_address(
            self, address: Address) -> Dict[TransactionHash, TryteString]:
        """
        Get all trytes from address
        """
        hashes = self.get_hashes_from_addr(address)
        trytes = self.get_trytes_from_hashes(hashes)
        if hashes and trytes:
            result = dict(zip(hashes, trytes))
        else:
            result = None
        return result

    @staticmethod
    def get_json_from_tryte(tryte: TryteString) -> Dict:
        try:
            str_from_tryte = tryte.as_string()
            dict_from_tryte = json.loads(str_from_tryte)
        except ValueError as e:
            logger.error("Failed to convet trytes to JSON", e)
            dict_from_tryte = None
        return dict_from_tryte

    def send_msg_to_addr(self, address: Address, msg: str, tag: str) -> Dict:
        """
        Sends msg on Tangle to address with a tag
        """
        try:
            response = self.iota_api.send_transfer(
                depth=2,
                transfers=[
                    ProposedTransaction(address=address,
                                        value=0,
                                        tag=Tag(tag),
                                        message=TryteString.from_string(msg))
                ])
        except BadApiResponse as e:
            logger.warning(
                "Message '" + msg + "' has failed to be stored in " +
                address.__str__(), e)
            response = None
        return response

    def get_bundles_from_addr(self, address: Address) -> List[Dict]:
        '''
        Retrive all bundles sent to this address from IRI
        # requres IRI 1.6+ (or it seems so)
        '''
        hashes = self.get_hashes_from_addr(address)
        bundles = []
        if hashes:
            for tx in hashes:
                try:
                    # have to loop through all txs, if tx is not 'tail' of a bundle then get_bundles() throws error
                    bundle = self.iota_api.get_bundles(tx)
                except BadApiResponse:
                    bundle = None

                if bundle:
                    bundles.append(bundle)
        return bundles

    def get_messages_from_bundles(self, bundles: List) -> Dict:
        """
        Loop through list of bundles and get string per bundle
        # requres IRI 1.6+ (or it seems so)
        """
        output_msgs = {}
        for bundle in bundles:
            tx_list = bundle['bundles'][0].as_json_compatible()
            msg = ''
            for tx in tx_list:
                # if its a bundle with iotas, just get text from first tx in bundle, the rest are signatures
                if tx['current_index'] == 0 and tx['value'] > 0:
                    msg = tx['signature_message_fragment'].as_string()
                    break
                # if its a bundle without iota value, then consequently get all message fields and join strings
                if tx['value'] == 0:
                    msg = msg + tx['signature_message_fragment'].as_string()
            bundle_hash = tx_list[0]['bundle_hash'].__str__()
            addr = tx_list[0]['address'].__str__()
            timestamp = tx_list[0]['timestamp']
            value = tx_list[0]['value']
            output_msgs[bundle_hash] = {
                'msg': msg,
                'address': addr,
                'timestamp': timestamp,
                'value': value
            }
        return output_msgs

    def get_all_msg_from_addr_by_bundle(self, address: Address) -> Dict:
        '''
        Get dict of all msg with timestamps from address by bundle hash as key
        # requres IRI 1.6+ (or it seems so)
        '''
        bundles = self.get_bundles_from_addr(address)
        hashes_and_msgs = self.get_messages_from_bundles(bundles)
        return hashes_and_msgs