Ejemplo n.º 1
0
def issue_milestone(address, api, index, *reference_transaction):
    txn1 = ProposedTransaction(address=Address(address), value=0)

    txn2 = ProposedTransaction(address=Address(address), value=0)

    bundle = ProposedBundle()
    bundle.add_transaction(txn1)
    bundle.add_transaction(txn2)

    bundle[0]._legacy_tag = Tag(converter.int_to_trytestring(index, 9))

    bundle_logic.finalize(bundle)

    tips = api.get_transactions_to_approve(depth=3)
    trunk = tips['trunkTransaction']
    if reference_transaction:
        branch = reference_transaction[0]
    else:
        branch = tips['branchTransaction']

    bundle_trytes = bundle.as_tryte_strings()
    milestone = api.attach_to_tangle(trunk, branch, bundle_trytes, 9)
    api.broadcast_and_store(milestone['trytes'])

    return milestone
Ejemplo n.º 2
0
    def Send(self, ReceiverAddress, Message, Test_Node=False):
        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)

        bundle = ProposedBundle()
        if type(ReceiverAddress) == list and type(Message) == list and (
                len(ReceiverAddress) == len(Message)):
            for i in range(len(ReceiverAddress)):
                Bundle_Generation(ReceiverAddress[i], Message[i])
        elif type(ReceiverAddress) == str and type(Message) == str:
            Bundle_Generation(ReceiverAddress, Message)

        bundle.finalize()
        coded = bundle.as_tryte_strings()
        hashed = bundle.hash

        #Return the fastest sender node from the DB if localhost is not present.
        if str(self.Node) != "http://localhost:14265":
            if Test_Node == False:
                self.Node = Return_Fastest_Node()["Send"]
        self.IOTA_Api = Iota(self.Node, seed=self.Seed_Copy)

        send = self.IOTA_Api.send_trytes(trytes=coded, depth=4)
        return hashed
Ejemplo n.º 3
0
 def mock_get_trytes(self, txnHashesAll):
     ret = {'trytes': []}
     for txnHash in txnHashesAll:
         for txn in self.transfers:
             if txn[0].hash == txnHash:
                 bundle = ProposedBundle()
                 bundle.add_transaction(txn[0])
                 bundle.finalize()
                 ret['trytes'].append(bundle.as_tryte_strings()[0])
     return ret
Ejemplo n.º 4
0
 def Send(self, ReceiverAddress, Message):
     text_transfer = TryteString.from_string(str(Message))
     #This now proposes a transaction to a person. The "message = ..." command is a message that the receiver should be able to decode once arrived.
     txn_2 = ProposedTransaction(address=Address(ReceiverAddress),
                                 message=text_transfer,
                                 value=0)
     #Now create a new bundle (i.e. propose a bundle)
     bundle = ProposedBundle()
     #Add the transaction "txn_2" to the bundle. We can also add several addresses for receiving but we get to that later.
     bundle.add_transaction(txn_2)
     bundle.finalize()
     coded = bundle.as_tryte_strings()
     send = self.api.send_trytes(trytes=coded, depth=4)
def send_transaction(node_url, address, tag, messages, values):
    propose_bundle = ProposedBundle()

    # Setting output transaction ...
    txn_output = ProposedTransaction(
        address = Address(address),
        value = values,
        tag = Tag(tag),
        message = TryteString.from_string(messages)
    )

    propose_bundle.add_transaction(txn_output)
    propose_bundle.finalize()
    trytes = propose_bundle.as_tryte_strings()

    api = Iota(node_url)

    # Tips
    trunk_hash, branch_hash = gtta(node_url)

    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
        tx_tryte = attach_to_tangle(node_url, trunk_hash, branch_hash, tx_tryte)

        # Prepare to store and broadcast ...
        try:
            api.broadcast_and_store(tx_tryte)
        except Exception as e:
            return str("Error: %s" % (str(e)))

        return str(propose_bundle.hash)
Ejemplo n.º 6
0
    def Send(self, ReceiverAddress, Message):
        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)

        bundle = ProposedBundle()
        if type(ReceiverAddress) == list and type(Message) == list and (
                len(ReceiverAddress) == len(Message)):
            for i in range(len(ReceiverAddress)):
                Bundle_Generation(ReceiverAddress[i], Message[i])
        elif type(ReceiverAddress) == str and type(Message) == str:
            Bundle_Generation(ReceiverAddress, Message)

        bundle.finalize()
        coded = bundle.as_tryte_strings()
        hashed = bundle.hash
        send = self.IOTA_Api.send_trytes(trytes=coded, depth=4)
        return hashed
Ejemplo n.º 7
0
    def Send(self, Receiver_Address, Message):
        if isinstance(Message, bytes):
            Message = Message.decode()
        Trytes_Convertion = TryteString.from_string(Message)
        TX = ProposedTransaction(address = Address(Receiver_Address), message = Trytes_Convertion, value = 0)
        bundle = ProposedBundle()
        bundle.add_transaction(TX)
        bundle.finalize()
        TX_Hash = str(bundle.hash)
        bundle_as_trytes = bundle.as_tryte_strings()
        TX_Success = False
        try:
            TX_Confirmation = self.IOTA_Api.send_trytes(trytes = bundle_as_trytes, depth = 4)
            TX_Success = TX_Hash
        except:
            if "iota.adapter.BadApiResponse" in str(sys.exc_info()[1]):
                print("Node not in Sync, finding another node....") #< ----------------------------------------------------

            elif "The subtangle has not been updated yet." in str(sys.exc_info()[1]):
                print("Node not synced yet, finding another node...") #< ----------------------------------------------------

            elif "429 response from node"in str(sys.exc_info()[1]):
                print("Too many requests to node, finding an alternative node...") #< ----------------------------------------------------

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

            elif "403 Forbidden" in str(sys.exc_info()[1]):
                print("No access granted to node, finding an alternative node...") #< ----------------------------------------------------
                # special case; a node accepts with POW set to "True"

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

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

        return TX_Success
Ejemplo n.º 8
0
    def _execute(self, request):
        # Required parameters.
        seed = request['seed']  # type: Seed
        bundle = ProposedBundle(request['transfers'])

        # Optional parameters.
        change_address = request.get(
            'changeAddress')  # type: Optional[Address]
        proposed_inputs = request.get(
            'inputs')  # type: Optional[List[Address]]

        want_to_spend = bundle.balance
        if want_to_spend > 0:
            # We are spending inputs, so we need to gather and sign them.
            if proposed_inputs is None:
                # No inputs provided.  Scan addresses for unspent inputs.
                gi_response = GetInputsCommand(self.adapter)(
                    seed=seed,
                    threshold=want_to_spend,
                )

                confirmed_inputs = gi_response['inputs']
            else:
                # Inputs provided.  Check to make sure we have sufficient
                # balance.
                available_to_spend = 0
                confirmed_inputs = []  # type: List[Address]

                gb_response = GetBalancesCommand(self.adapter)(
                    addresses=[i.address for i in proposed_inputs], )

                for i, balance in enumerate(gb_response.get('balances') or []):
                    input_ = proposed_inputs[i]

                    if balance > 0:
                        available_to_spend += balance

                        # Update the address balance from the API response, just in
                        # case somebody tried to cheat.
                        input_.balance = balance
                        confirmed_inputs.append(input_)

                if available_to_spend < want_to_spend:
                    raise with_context(
                        exc=BadApiResponse(
                            'Insufficient balance; found {found}, need {need} '
                            '(``exc.context`` has more info).'.format(
                                found=available_to_spend,
                                need=want_to_spend,
                            ), ),
                        context={
                            'available_to_spend': available_to_spend,
                            'confirmed_inputs': confirmed_inputs,
                            'request': request,
                            'want_to_spend': want_to_spend,
                        },
                    )

            bundle.add_inputs(confirmed_inputs)

            if bundle.balance < 0:
                if not change_address:
                    change_address =\
                      GetNewAddressesCommand(self.adapter)(seed=seed)['addresses'][0]

                bundle.send_unspent_inputs_to(change_address)

            bundle.finalize()

            if confirmed_inputs:
                bundle.sign_inputs(KeyGenerator(seed))
        else:
            bundle.finalize()

        return {
            'trytes': bundle.as_tryte_strings(),
        }
bundle.finalize()
bundle.sign_inputs(KeyGenerator(b'BXOM9LUNLPSEXBRJV9UUNLHSUHABEOGHQOGNBNBUEYSGOFZOEPYKEYRSFTXBOEJLUODUQXXGQ9NWQBSGH'))

tips = json.loads(call_iota_api(getTips))
print("llsdldld")
for x in tips['hashes']:
    getTransactionsToApprove = {"command": "getTransactionsToApprove", "depth": 15, "reference": x}
    result = json.loads(call_iota_api(getTransactionsToApprove))
    if "exception" in result:
        print(result)
        continue
    elif "error" in result:
        print(result)
        continue
    else:
        print(result)
        trunk_hash = result['trunkTransaction']
        branch_hash = result['branchTransaction']
        break
#prev_tx = None
trytes = bundle.as_tryte_strings()
Tlist = list()
for x in trytes:
    Tlist.append(str(x))
attachToTangle = {"command": "attachToTangle", "trunkTransaction": trunk_hash, "branchTransaction": branch_hash, "minWeightMagnitude": 18, "trytes": Tlist}
#print(json.dumps(attachToTangle))
output = call_iota_api(attachToTangle)
fw = open('output.json','w')
fw.write(json.dumps(output))
fw.close()
Ejemplo n.º 10
0
  def _execute(self, request):
    # Required parameters.
    seed      = request['seed'] # type: Seed
    bundle    = ProposedBundle(request['transfers'])

    # Optional parameters.
    change_address  = request.get('changeAddress') # type: Optional[Address]
    proposed_inputs = request.get('inputs') # type: Optional[List[Address]]

    want_to_spend = bundle.balance
    if want_to_spend > 0:
      # We are spending inputs, so we need to gather and sign them.
      if proposed_inputs is None:
        # No inputs provided.  Scan addresses for unspent inputs.
        gi_response = GetInputsCommand(self.adapter)(
          seed      = seed,
          threshold = want_to_spend,
        )

        confirmed_inputs = gi_response['inputs']
      else:
        # Inputs provided.  Check to make sure we have sufficient
        # balance.
        available_to_spend  = 0
        confirmed_inputs    = [] # type: List[Address]

        gb_response = GetBalancesCommand(self.adapter)(
          addresses = [i.address for i in proposed_inputs],
        )

        for i, balance in enumerate(gb_response.get('balances') or []):
          input_ = proposed_inputs[i]

          if balance > 0:
            available_to_spend += balance

            # Update the address balance from the API response, just in
            # case somebody tried to cheat.
            input_.balance = balance
            confirmed_inputs.append(input_)

        if available_to_spend < want_to_spend:
          raise with_context(
            exc = BadApiResponse(
              'Insufficient balance; found {found}, need {need} '
              '(``exc.context`` has more info).'.format(
                found = available_to_spend,
                need  = want_to_spend,
              ),
            ),

            context = {
              'available_to_spend': available_to_spend,
              'confirmed_inputs':   confirmed_inputs,
              'request':            request,
              'want_to_spend':      want_to_spend,
            },
          )

      bundle.add_inputs(confirmed_inputs)

      if bundle.balance < 0:
        if not change_address:
          change_address =\
            GetNewAddressesCommand(self.adapter)(seed=seed)['addresses'][0]

        bundle.send_unspent_inputs_to(change_address)

      bundle.finalize()

      if confirmed_inputs:
        bundle.sign_inputs(KeyGenerator(seed))
    else:
      bundle.finalize()

    return {
      'trytes': bundle.as_tryte_strings(),
    }