This repository was archived by the owner on Jan 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathapi.py
1109 lines (855 loc) · 34.4 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from six import with_metaclass
from typing import Dict, Iterable, Optional, Text
from iota import AdapterSpec, Address, Tag, TryteString, TrytesCompatible
from iota.adapter import BaseAdapter, resolve_adapter
from iota.commands import BaseCommand, CustomCommand, core, \
discover_commands, extended
from iota.commands.extended.helpers import Helpers
from iota.crypto.addresses import AddressGenerator
from iota.crypto.types import Seed
from iota.transaction.creation import ProposedTransaction
from iota.transaction.types import BundleHash, TransactionHash, \
TransactionTrytes
__all__ = [
'InvalidCommand',
'Iota',
'StrictIota',
]
class InvalidCommand(ValueError):
"""
Indicates that an invalid command name was specified.
"""
pass
class ApiMeta(type):
"""
Manages command registries for IOTA API base classes.
"""
def __init__(cls, name, bases=None, attrs=None):
super(ApiMeta, cls).__init__(name, bases, attrs)
if not hasattr(cls, 'commands'):
cls.commands = {}
# Copy command registry from base class to derived class, but
# in the event of a conflict, preserve the derived class'
# commands.
commands = {}
for base in bases:
if isinstance(base, ApiMeta):
commands.update(base.commands)
if commands:
commands.update(cls.commands)
cls.commands = commands
class StrictIota(with_metaclass(ApiMeta)):
"""
API to send HTTP requests for communicating with an IOTA node.
This implementation only exposes the "core" API methods. For a more
feature-complete implementation, use :py:class:`Iota` instead.
References:
- https://iota.readme.io/docs/getting-started
"""
commands = discover_commands('iota.commands.core')
def __init__(self, adapter, testnet=False):
# type: (AdapterSpec, bool) -> None
"""
:param adapter:
URI string or BaseAdapter instance.
:param testnet:
Whether to use testnet settings for this instance.
"""
super(StrictIota, self).__init__()
if not isinstance(adapter, BaseAdapter):
adapter = resolve_adapter(adapter)
self.adapter = adapter # type: BaseAdapter
self.testnet = testnet
def __getattr__(self, command):
# type: (Text) -> BaseCommand
"""
Creates a pre-configured command instance.
This method will only return commands supported by the API
class.
If you want to execute an arbitrary API command, use
:py:meth:`create_command`.
:param command:
The name of the command to create.
References:
- https://iota.readme.io/docs/making-requests
"""
# Fix an error when invoking :py:func:`help`.
# https://github.com/iotaledger/iota.lib.py/issues/41
if command == '__name__':
# noinspection PyTypeChecker
return None
try:
command_class = self.commands[command]
except KeyError:
raise InvalidCommand(
'{cls} does not support {command!r} command.'.format(
cls=type(self).__name__,
command=command,
),
)
return command_class(self.adapter)
def create_command(self, command):
# type: (Text) -> CustomCommand
"""
Creates a pre-configured CustomCommand instance.
This method is useful for invoking undocumented or experimental
methods, or if you just want to troll your node for awhile.
:param command:
The name of the command to create.
"""
return CustomCommand(self.adapter, command)
@property
def default_min_weight_magnitude(self):
# type: () -> int
"""
Returns the default ``min_weight_magnitude`` value to use for
API requests.
"""
return 9 if self.testnet else 14
def add_neighbors(self, uris):
# type: (Iterable[Text]) -> dict
"""
Add one or more neighbors to the node. Lasts until the node is
restarted.
:param uris:
Use format ``<protocol>://<ip address>:<port>``.
Example: ``add_neighbors(['udp://example.com:14265'])``
.. note::
These URIs are for node-to-node communication (e.g.,
weird things will happen if you specify a node's HTTP
API URI here).
References:
- https://iota.readme.io/docs/addneighors
"""
return core.AddNeighborsCommand(self.adapter)(uris=uris)
def attach_to_tangle(
self,
trunk_transaction, # type: TransactionHash
branch_transaction, # type: TransactionHash
trytes, # type: Iterable[TryteString]
min_weight_magnitude=None, # type: Optional[int]
):
# type: (...) -> dict
"""
Attaches the specified transactions (trytes) to the Tangle by
doing Proof of Work. You need to supply branchTransaction as
well as trunkTransaction (basically the tips which you're going
to validate and reference with this transaction) - both of which
you'll get through the getTransactionsToApprove API call.
The returned value is a different set of tryte values which you
can input into :py:meth:`broadcast_transactions` and
:py:meth:`store_transactions`.
References:
- https://iota.readme.io/docs/attachtotangle
"""
if min_weight_magnitude is None:
min_weight_magnitude = self.default_min_weight_magnitude
return core.AttachToTangleCommand(self.adapter)(
trunkTransaction=trunk_transaction,
branchTransaction=branch_transaction,
minWeightMagnitude=min_weight_magnitude,
trytes=trytes,
)
def broadcast_transactions(self, trytes):
# type: (Iterable[TryteString]) -> dict
"""
Broadcast a list of transactions to all neighbors.
The input trytes for this call are provided by
:py:meth:`attach_to_tangle`.
References:
- https://iota.readme.io/docs/broadcasttransactions
"""
return core.BroadcastTransactionsCommand(self.adapter)(trytes=trytes)
def check_consistency(self, tails):
# type: (Iterable[TransactionHash]) -> dict
"""
Used to ensure tail resolves to a consistent ledger which is
necessary to validate before attempting promotionChecks
transaction hashes for promotability.
This is called with a pending transaction (or more of them) and
it will tell you if it is still possible for this transaction
(or all the transactions simultaneously if you give more than
one) to be confirmed, or not (because it conflicts with another
already confirmed transaction).
:param tails:
Transaction hashes. Must be tail transactions.
:return:
Dict with the following structure::
{
'state': bool,
'info': str,
This field will only exist set if ``state`` is
``False``.
}
"""
return core.CheckConsistencyCommand(self.adapter)(
tails=tails,
)
def find_transactions(
self,
bundles=None, # type: Optional[Iterable[BundleHash]]
addresses=None, # type: Optional[Iterable[Address]]
tags=None, # type: Optional[Iterable[Tag]]
approvees=None, # type: Optional[Iterable[TransactionHash]]
):
# type: (...) -> dict
"""
Find the transactions which match the specified input and
return.
All input values are lists, for which a list of return values
(transaction hashes), in the same order, is returned for all
individual elements.
Using multiple of these input fields returns the intersection of
the values.
:param bundles:
List of bundle IDs.
:param addresses:
List of addresses.
:param tags:
List of tags.
:param approvees:
List of approvee transaction IDs.
References:
- https://iota.readme.io/docs/findtransactions
"""
return core.FindTransactionsCommand(self.adapter)(
bundles=bundles,
addresses=addresses,
tags=tags,
approvees=approvees,
)
def get_balances(self, addresses, threshold=100):
# type: (Iterable[Address], int) -> dict
"""
Similar to :py:meth:`get_inclusion_states`. Returns the
confirmed balance which a list of addresses have at the latest
confirmed milestone.
In addition to the balances, it also returns the milestone as
well as the index with which the confirmed balance was
determined. The balances are returned as a list in the same
order as the addresses were provided as input.
:param addresses:
List of addresses to get the confirmed balance for.
:param threshold:
Confirmation threshold.
References:
- https://iota.readme.io/docs/getbalances
"""
return core.GetBalancesCommand(self.adapter)(
addresses=addresses,
threshold=threshold,
)
def get_inclusion_states(self, transactions, tips):
# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict
"""
Get the inclusion states of a set of transactions. This is for
determining if a transaction was accepted and confirmed by the
network or not. You can search for multiple tips (and thus,
milestones) to get past inclusion states of transactions.
:param transactions:
List of transactions you want to get the inclusion state
for.
:param tips:
List of tips (including milestones) you want to search for
the inclusion state.
References:
- https://iota.readme.io/docs/getinclusionstates
"""
return core.GetInclusionStatesCommand(self.adapter)(
transactions=transactions,
tips=tips,
)
def get_neighbors(self):
# type: () -> dict
"""
Returns the set of neighbors the node is connected with, as well
as their activity count.
The activity counter is reset after restarting IRI.
References:
- https://iota.readme.io/docs/getneighborsactivity
"""
return core.GetNeighborsCommand(self.adapter)()
def get_node_info(self):
# type: () -> dict
"""
Returns information about the node.
References:
- https://iota.readme.io/docs/getnodeinfo
"""
return core.GetNodeInfoCommand(self.adapter)()
def get_tips(self):
# type: () -> dict
"""
Returns the list of tips (transactions which have no other
transactions referencing them).
References:
- https://iota.readme.io/docs/gettips
- https://iota.readme.io/docs/glossary#iota-terms
"""
return core.GetTipsCommand(self.adapter)()
def get_transactions_to_approve(self, depth):
# type: (int) -> dict
"""
Tip selection which returns ``trunkTransaction`` and
``branchTransaction``.
:param depth:
Determines how many bundles to go back to when finding the
transactions to approve.
The higher the depth value, the more "babysitting" the node
will perform for the network (as it will confirm more
transactions that way).
References:
- https://iota.readme.io/docs/gettransactionstoapprove
"""
return core.GetTransactionsToApproveCommand(self.adapter)(depth=depth)
def get_trytes(self, hashes):
# type: (Iterable[TransactionHash]) -> dict
"""
Returns the raw transaction data (trytes) of one or more
transactions.
References:
- https://iota.readme.io/docs/gettrytes
"""
return core.GetTrytesCommand(self.adapter)(hashes=hashes)
def interrupt_attaching_to_tangle(self):
# type: () -> dict
"""
Interrupts and completely aborts the :py:meth:`attach_to_tangle`
process.
References:
- https://iota.readme.io/docs/interruptattachingtotangle
"""
return core.InterruptAttachingToTangleCommand(self.adapter)()
def remove_neighbors(self, uris):
# type: (Iterable[Text]) -> dict
"""
Removes one or more neighbors from the node. Lasts until the
node is restarted.
:param uris:
Use format ``<protocol>://<ip address>:<port>``.
Example: `remove_neighbors(['udp://example.com:14265'])`
References:
- https://iota.readme.io/docs/removeneighors
"""
return core.RemoveNeighborsCommand(self.adapter)(uris=uris)
def store_transactions(self, trytes):
# type: (Iterable[TryteString]) -> dict
"""
Store transactions into local storage.
The input trytes for this call are provided by
:py:meth:`attach_to_tangle`.
References:
- https://iota.readme.io/docs/storetransactions
"""
return core.StoreTransactionsCommand(self.adapter)(trytes=trytes)
def were_addresses_spent_from(self, addresses):
# type: (Iterable[Address]) -> dict
"""
Check if a list of addresses was ever spent from, in the current
epoch, or in previous epochs.
:param addresses:
List of addresses to check.
References:
- https://iota.readme.io/docs/wereaddressesspentfrom
"""
return core.WereAddressesSpentFromCommand(self.adapter)(
addresses=addresses,
)
class Iota(StrictIota):
"""
Implements the core API, plus additional wrapper methods for common
operations.
References:
- https://iota.readme.io/docs/getting-started
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md
"""
commands = discover_commands('iota.commands.extended')
def __init__(self, adapter, seed=None, testnet=False):
# type: (AdapterSpec, Optional[TrytesCompatible], bool) -> None
"""
:param seed:
Seed used to generate new addresses.
If not provided, a random one will be generated.
.. note::
This value is never transferred to the node/network.
"""
super(Iota, self).__init__(adapter, testnet)
self.seed = Seed(seed) if seed else Seed.random()
self.helpers = Helpers(self)
def broadcast_and_store(self, trytes):
# type: (Iterable[TransactionTrytes]) -> dict
"""
Broadcasts and stores a set of transaction trytes.
:return:
Dict with the following structure::
{
'trytes': List[TransactionTrytes],
List of TransactionTrytes that were broadcast.
Same as the input ``trytes``.
}
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#broadcastandstore
"""
return extended.BroadcastAndStoreCommand(self.adapter)(trytes=trytes)
def get_account_data(self, start=0, stop=None, inclusion_states=False, security_level=None):
# type: (int, Optional[int], bool, Optional[int]) -> dict
"""
More comprehensive version of :py:meth:`get_transfers` that
returns addresses and account balance in addition to bundles.
This function is useful in getting all the relevant information
of your account.
:param start:
Starting key index.
:param stop:
Stop before this index.
Note that this parameter behaves like the ``stop`` attribute
in a :py:class:`slice` object; the stop index is *not*
included in the result.
If ``None`` (default), then this method will check every
address until it finds one without any transfers.
:param inclusion_states:
Whether to also fetch the inclusion states of the transfers.
This requires an additional API call to the node, so it is
disabled by default.
:param security_level:
Number of iterations to use when generating new addresses
(see :py:meth:`get_new_addresses`).
This value must be between 1 and 3, inclusive.
If not set, defaults to
:py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`.
:return:
Dict with the following structure::
{
'addresses': List[Address],
List of generated addresses.
Note that this list may include unused
addresses.
'balance': int,
Total account balance. Might be 0.
'bundles': List[Bundle],
List of bundles with transactions to/from this
account.
}
"""
return extended.GetAccountDataCommand(self.adapter)(
seed=self.seed,
start=start,
stop=stop,
inclusionStates=inclusion_states,
security_level=security_level
)
def get_bundles(self, transaction):
# type: (TransactionHash) -> dict
"""
Returns the bundle(s) associated with the specified transaction
hash.
:param transaction:
Transaction hash. Must be a tail transaction.
:return:
Dict with the following structure::
{
'bundles': List[Bundle],
List of matching bundles. Note that this value is
always a list, even if only one bundle was found.
}
:raise:
- :py:class:`iota.adapter.BadApiResponse` if any of the
bundles fails validation.
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#getbundle
"""
return extended.GetBundlesCommand(self.adapter)(transaction=transaction)
def get_inputs(
self,
start=0,
stop=None,
threshold=None,
security_level=None,
):
# type: (int, Optional[int], Optional[int], Optional[int]) -> dict
"""
Gets all possible inputs of a seed and returns them, along with
the total balance.
This is either done deterministically (by generating all
addresses until :py:meth:`find_transactions` returns an empty
result), or by providing a key range to search.
:param start:
Starting key index.
Defaults to 0.
:param stop:
Stop before this index.
Note that this parameter behaves like the ``stop`` attribute
in a :py:class:`slice` object; the stop index is *not*
included in the result.
If ``None`` (default), then this method will not stop until
it finds an unused address.
:param threshold:
If set, determines the minimum threshold for a successful
result:
- As soon as this threshold is reached, iteration will stop.
- If the command runs out of addresses before the threshold
is reached, an exception is raised.
.. note::
This method does not attempt to "optimize" the result
(e.g., smallest number of inputs, get as close to
``threshold`` as possible, etc.); it simply accumulates
inputs in order until the threshold is met.
If ``threshold`` is 0, the first address in the key range
with a non-zero balance will be returned (if it exists).
If ``threshold`` is ``None`` (default), this method will
return **all** inputs in the specified key range.
:param security_level:
Number of iterations to use when generating new addresses
(see :py:meth:`get_new_addresses`).
This value must be between 1 and 3, inclusive.
If not set, defaults to
:py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`.
:return:
Dict with the following structure::
{
'inputs': List[Address],
Addresses with nonzero balances that can be used
as inputs.
'totalBalance': int,
Aggregate balance from all matching addresses.
}
Note that each Address in the result has its ``balance``
attribute set.
Example:
.. code-block:: python
response = iota.get_inputs(...)
input0 = response['inputs'][0] # type: Address
input0.balance # 42
:raise:
- :py:class:`iota.adapter.BadApiResponse` if ``threshold``
is not met. Not applicable if ``threshold`` is ``None``.
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#getinputs
"""
return extended.GetInputsCommand(self.adapter)(
seed=self.seed,
start=start,
stop=stop,
threshold=threshold,
securityLevel=security_level
)
def get_latest_inclusion(self, hashes):
# type: (Iterable[TransactionHash]) -> Dict[TransactionHash, bool]
"""
Fetches the inclusion state for the specified transaction
hashes, as of the latest milestone that the node has processed.
Effectively, this is ``getNodeInfo`` + ``getInclusionStates``.
:param hashes:
Iterable of transaction hashes.
:return:
Dict with the following structure::
{
"states": Dict[TransactionHash, bool]
Dict with one boolean per transaction hash in
``hashes``.
}
"""
return extended.GetLatestInclusionCommand(self.adapter)(hashes=hashes)
def get_new_addresses(
self,
index=0,
count=1,
security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
checksum=False,
):
# type: (int, Optional[int], int, bool) -> dict
"""
Generates one or more new addresses from the seed.
:param index:
The key index of the first new address to generate (must be
>= 1).
:param count:
Number of addresses to generate (must be >= 1).
.. tip::
This is more efficient than calling ``get_new_address``
inside a loop.
If ``None``, this method will progressively generate
addresses and scan the Tangle until it finds one that has no
transactions referencing it.
:param security_level:
Number of iterations to use when generating new addresses.
Larger values take longer, but the resulting signatures are
more secure.
This value must be between 1 and 3, inclusive.
:param checksum:
Specify whether to return the address with the checksum.
Defaults to ``False``.
:return:
Dict with the following structure::
{
'addresses': List[Address],
Always a list, even if only one address was
generated.
}
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#getnewaddress
"""
return extended.GetNewAddressesCommand(self.adapter)(
count=count,
index=index,
securityLevel=security_level,
checksum=checksum,
seed=self.seed,
)
def get_transfers(self, start=0, stop=None, inclusion_states=False):
# type: (int, Optional[int], bool) -> dict
"""
Returns all transfers associated with the seed.
:param start:
Starting key index.
:param stop:
Stop before this index.
Note that this parameter behaves like the ``stop`` attribute
in a :py:class:`slice` object; the stop index is *not*
included in the result.
If ``None`` (default), then this method will check every
address until it finds one without any transfers.
:param inclusion_states:
Whether to also fetch the inclusion states of the transfers.
This requires an additional API call to the node, so it is
disabled by default.
:return:
Dict with the following structure::
{
'bundles': List[Bundle],
Matching bundles, sorted by tail transaction
timestamp.
This value is always a list, even if only one
bundle was found.
}
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#gettransfers
"""
return extended.GetTransfersCommand(self.adapter)(
seed=self.seed,
start=start,
stop=stop,
inclusionStates=inclusion_states,
)
def prepare_transfer(
self,
transfers, # type: Iterable[ProposedTransaction]
inputs=None, # type: Optional[Iterable[Address]]
change_address=None, # type: Optional[Address]
security_level=None, # type: Optional[int]
):
# type: (...) -> dict
"""
Prepares transactions to be broadcast to the Tangle, by
generating the correct bundle, as well as choosing and signing
the inputs (for value transfers).
:param transfers:
Transaction objects to prepare.
:param inputs:
List of addresses used to fund the transfer.
Ignored for zero-value transfers.
If not provided, addresses will be selected automatically by
scanning the Tangle for unspent inputs. Depending on how
many transfers you've already sent with your seed, this
process could take awhile.
:param change_address:
If inputs are provided, any unspent amount will be sent to
this address.
If not specified, a change address will be generated
automatically.
:param security_level:
Number of iterations to use when generating new addresses
(see :py:meth:`get_new_addresses`).
This value must be between 1 and 3, inclusive.
If not set, defaults to
:py:attr:`AddressGenerator.DEFAULT_SECURITY_LEVEL`.
:return:
Dict with the following structure::
{
'trytes': List[TransactionTrytes],
Raw trytes for the transactions in the bundle,
ready to be provided to :py:meth:`send_trytes`.
}
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#preparetransfers
"""
return extended.PrepareTransferCommand(self.adapter)(
seed=self.seed,
transfers=transfers,
inputs=inputs,
changeAddress=change_address,
securityLevel=security_level,
)
def promote_transaction(
self,
transaction,
depth=3,
min_weight_magnitude=None,
):
# type: (TransactionHash, int, Optional[int]) -> dict
"""
Promotes a transaction by adding spam on top of it.
:return:
Dict with the following structure::
{
'bundle': Bundle,
The newly-published bundle.
}
"""
if min_weight_magnitude is None:
min_weight_magnitude = self.default_min_weight_magnitude
return extended.PromoteTransactionCommand(self.adapter)(
transaction=transaction,
depth=depth,
minWeightMagnitude=min_weight_magnitude,
)
def replay_bundle(
self,
transaction,
depth=3,
min_weight_magnitude=None,
):
# type: (TransactionHash, int, Optional[int]) -> dict
"""
Takes a tail transaction hash as input, gets the bundle
associated with the transaction and then replays the bundle by
attaching it to the Tangle.
:param transaction:
Transaction hash. Must be a tail.
:param depth:
Depth at which to attach the bundle.
Defaults to 3.
:param min_weight_magnitude:
Min weight magnitude, used by the node to calibrate Proof of
Work.
If not provided, a default value will be used.
:return:
Dict with the following structure::
{
'trytes': List[TransactionTrytes],
Raw trytes that were published to the Tangle.
}
References:
- https://github.com/iotaledger/wiki/blob/master/api-proposal.md#replaytransfer
"""
if min_weight_magnitude is None:
min_weight_magnitude = self.default_min_weight_magnitude
return extended.ReplayBundleCommand(self.adapter)(
transaction=transaction,
depth=depth,
minWeightMagnitude=min_weight_magnitude,
)
def send_transfer(
self,
transfers, # type: Iterable[ProposedTransaction]
depth=3, # type: int
inputs=None, # type: Optional[Iterable[Address]]
change_address=None, # type: Optional[Address]
min_weight_magnitude=None, # type: Optional[int]
security_level=None, # type: Optional[int]
):
# type: (...) -> dict
"""
Prepares a set of transfers and creates the bundle, then
attaches the bundle to the Tangle, and broadcasts and stores the
transactions.
:param transfers:
Transfers to include in the bundle.
:param depth:
Depth at which to attach the bundle.
Defaults to 3.
:param inputs:
List of inputs used to fund the transfer.
Not needed for zero-value transfers.
:param change_address:
If inputs are provided, any unspent amount will be sent to
this address.
If not specified, a change address will be generated
automatically.