/
client.py
2409 lines (1922 loc) · 81.6 KB
/
client.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 -*-
"""IPFS API Bindings for Python.
Classes:
* Client – a TCP client for interacting with an IPFS daemon
"""
from __future__ import absolute_import
import os
import warnings
from . import http, multipart, utils, exceptions, encoding
DEFAULT_HOST = str(os.environ.get("PY_IPFSAPI_DEFAULT_HOST", 'localhost'))
DEFAULT_PORT = int(os.environ.get("PY_IPFSAPI_DEFAULT_PORT", 5001))
DEFAULT_BASE = str(os.environ.get("PY_IPFSAPI_DEFAULT_BASE", 'api/v0'))
VERSION_MINIMUM = "0.4.3"
VERSION_MAXIMUM = "0.5.0"
def assert_version(version, minimum=VERSION_MINIMUM, maximum=VERSION_MAXIMUM):
"""Make sure that the given daemon version is supported by this client
version.
Raises
------
~ipfsapi.exceptions.VersionMismatch
Parameters
----------
version : str
The version of an IPFS daemon.
minimum : str
The minimal IPFS version to allow.
maximum : str
The maximum IPFS version to allow.
"""
# Convert version strings to integer tuples
version = list(map(int, version.split('-', 1)[0].split('.')))
minimum = list(map(int, minimum.split('-', 1)[0].split('.')))
maximum = list(map(int, maximum.split('-', 1)[0].split('.')))
if minimum > version or version >= maximum:
raise exceptions.VersionMismatch(version, minimum, maximum)
def connect(host=DEFAULT_HOST, port=DEFAULT_PORT, base=DEFAULT_BASE,
chunk_size=multipart.default_chunk_size, **defaults):
"""Create a new :class:`~ipfsapi.Client` instance and connect to the
daemon to validate that its version is supported.
Raises
------
~ipfsapi.exceptions.VersionMismatch
~ipfsapi.exceptions.ErrorResponse
~ipfsapi.exceptions.ConnectionError
~ipfsapi.exceptions.ProtocolError
~ipfsapi.exceptions.StatusError
~ipfsapi.exceptions.TimeoutError
All parameters are identical to those passed to the constructor of the
:class:`~ipfsapi.Client` class.
Returns
-------
~ipfsapi.Client
"""
# Create client instance
client = Client(host, port, base, chunk_size, **defaults)
# Query version number from daemon and validate it
assert_version(client.version()['Version'])
return client
class SubChannel:
"""
Wrapper for a pubsub subscription object that allows for easy
closing of subscriptions.
"""
def __init__(self, sub):
self.__sub = sub
def read_message(self):
return next(self.__sub)
def __iter__(self):
return self.__sub
def close(self):
self.__sub.close()
def __enter__(self):
return self
def __exit__(self, *a):
self.close()
class Client(object):
"""A TCP client for interacting with an IPFS daemon.
A :class:`~ipfsapi.Client` instance will not actually establish a
connection to the daemon until at least one of it's methods is called.
Parameters
----------
host : str
Hostname or IP address of the computer running the ``ipfs daemon``
node (defaults to the local system)
port : int
The API port of the IPFS deamon (usually 5001)
base : str
Path of the deamon's API (currently always ``api/v0``)
chunk_size : int
The size of the chunks to break uploaded files and text content into
"""
_clientfactory = http.HTTPClient
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT,
base=DEFAULT_BASE, chunk_size=multipart.default_chunk_size,
**defaults):
"""Connects to the API port of an IPFS node."""
self.chunk_size = chunk_size
self._client = self._clientfactory(host, port, base, **defaults)
def add(self, files, recursive=False, pattern='**', *args, **kwargs):
"""Add a file, or directory of files to IPFS.
.. code-block:: python
>>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f:
... numbytes = f.write('Mary had a little lamb')
>>> c.add('nurseryrhyme.txt')
{'Hash': 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBKaxJdhaPab',
'Name': 'nurseryrhyme.txt'}
Parameters
----------
files : str
A filepath to either a file or directory
recursive : bool
Controls if files in subdirectories are added or not
pattern : str | list
Single `*glob* <https://docs.python.org/3/library/glob.html>`_
pattern or list of *glob* patterns and compiled regular expressions
to match the names of the filepaths to keep
trickle : bool
Use trickle-dag format (optimized for streaming) when generating
the dag; see `the FAQ <https://github.com/ipfs/faq/issues/218>` for
more information (Default: ``False``)
only_hash : bool
Only chunk and hash, but do not write to disk (Default: ``False``)
wrap_with_directory : bool
Wrap files with a directory object to preserve their filename
(Default: ``False``)
chunker : str
The chunking algorithm to use
pin : bool
Pin this object when adding (Default: ``True``)
Returns
-------
dict: File name and hash of the added file node
"""
#PY2: No support for kw-only parameters after glob parameters
opts = {
"trickle": kwargs.pop("trickle", False),
"only-hash": kwargs.pop("only_hash", False),
"wrap-with-directory": kwargs.pop("wrap_with_directory", False),
"pin": kwargs.pop("pin", True)
}
if "chunker" in kwargs:
opts["chunker"] = kwargs.pop("chunker")
kwargs.setdefault("opts", opts)
body, headers = multipart.stream_filesystem_node(
files, recursive, pattern, self.chunk_size
)
return self._client.request('/add', decoder='json',
data=body, headers=headers, **kwargs)
def get(self, multihash, **kwargs):
"""Downloads a file, or directory of files from IPFS.
Files are placed in the current working directory.
Parameters
----------
multihash : str
The path to the IPFS object(s) to be outputted
"""
args = (multihash,)
return self._client.download('/get', args, **kwargs)
def cat(self, multihash, offset=0, length=-1, **kwargs):
r"""Retrieves the contents of a file identified by hash.
.. code-block:: python
>>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
Traceback (most recent call last):
...
ipfsapi.exceptions.Error: this dag node is a directory
>>> c.cat('QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX')
b'<!DOCTYPE html>\n<html>\n\n<head>\n<title>ipfs example viewer</…'
Parameters
----------
multihash : str
The path to the IPFS object(s) to be retrieved
offset : int
Byte offset to begin reading from
length : int
Maximum number of bytes to read(-1 for all)
Returns
-------
str : File contents
"""
opts = {}
if offset != 0:
opts['offset'] = offset
if length != -1:
opts['length'] = length
args = (multihash,)
return self._client.request('/cat', args, opts=opts, **kwargs)
def ls(self, multihash, **kwargs):
"""Returns a list of objects linked to by the given hash.
.. code-block:: python
>>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Objects': [
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174, 'Type': 2},
…
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55, 'Type': 2}
]}
]}
Parameters
----------
multihash : str
The path to the IPFS object(s) to list links from
Returns
-------
dict : Directory information and contents
"""
args = (multihash,)
return self._client.request('/ls', args, decoder='json', **kwargs)
def refs(self, multihash, **kwargs):
"""Returns a list of hashes of objects referenced by the given hash.
.. code-block:: python
>>> c.refs('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTi … eXJY', 'Err': ''}]
Parameters
----------
multihash : str
Path to the object(s) to list refs from
Returns
-------
list
"""
args = (multihash,)
return self._client.request('/refs', args, decoder='json', **kwargs)
def refs_local(self, **kwargs):
"""Displays the hashes of all local objects.
.. code-block:: python
>>> c.refs_local()
[{'Ref': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7 … cNMV', 'Err': ''},
…
{'Ref': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTi … eXJY', 'Err': ''}]
Returns
-------
list
"""
return self._client.request('/refs/local', decoder='json', **kwargs)
def block_stat(self, multihash, **kwargs):
"""Returns a dict with the size of the block with the given hash.
.. code-block:: python
>>> c.block_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Key': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 258}
Parameters
----------
multihash : str
The base58 multihash of an existing block to stat
Returns
-------
dict : Information about the requested block
"""
args = (multihash,)
return self._client.request('/block/stat', args,
decoder='json', **kwargs)
def block_get(self, multihash, **kwargs):
r"""Returns the raw contents of a block.
.. code-block:: python
>>> c.block_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x121\n"\x12 \xdaW>\x14\xe5\xc1\xf6\xe4\x92\xd1 … \n\x02\x08\x01'
Parameters
----------
multihash : str
The base58 multihash of an existing block to get
Returns
-------
str : Value of the requested block
"""
args = (multihash,)
return self._client.request('/block/get', args, **kwargs)
def block_put(self, file, **kwargs):
"""Stores the contents of the given file object as an IPFS block.
.. code-block:: python
>>> c.block_put(io.BytesIO(b'Mary had a little lamb'))
{'Key': 'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'Size': 22}
Parameters
----------
file : io.RawIOBase
The data to be stored as an IPFS block
Returns
-------
dict : Information about the new block
See :meth:`~ipfsapi.Client.block_stat`
"""
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/block/put', decoder='json',
data=body, headers=headers, **kwargs)
def bitswap_wantlist(self, peer=None, **kwargs):
"""Returns blocks currently on the bitswap wantlist.
.. code-block:: python
>>> c.bitswap_wantlist()
{'Keys': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K',
'QmVQ1XvYGF19X4eJqz1s7FJYJqAxFC4oqh3vWJJEXn66cp'
]}
Parameters
----------
peer : str
Peer to show wantlist for.
Returns
-------
dict : List of wanted blocks
"""
args = (peer,)
return self._client.request('/bitswap/wantlist', args,
decoder='json', **kwargs)
def bitswap_stat(self, **kwargs):
"""Returns some diagnostic information from the bitswap agent.
.. code-block:: python
>>> c.bitswap_stat()
{'BlocksReceived': 96,
'DupBlksReceived': 73,
'DupDataReceived': 2560601,
'ProviderBufLen': 0,
'Peers': [
'QmNZFQRxt9RMNm2VVtuV2Qx7q69bcMWRVXmr5CEkJEgJJP',
'QmNfCubGpwYZAQxX8LQDsYgB48C4GbfZHuYdexpX9mbNyT',
'QmNfnZ8SCs3jAtNPc8kf3WJqJqSoX7wsX7VqkLdEYMao4u',
…
],
'Wantlist': [
'QmeV6C6XVt1wf7V7as7Yak3mxPma8jzpqyhtRtCvpKcfBb',
'QmdCWFLDXqgdWQY9kVubbEHBbkieKd3uo7MtCm7nTZZE9K',
'QmVQ1XvYGF19X4eJqz1s7FJYJqAxFC4oqh3vWJJEXn66cp'
]
}
Returns
-------
dict : Statistics, peers and wanted blocks
"""
return self._client.request('/bitswap/stat', decoder='json', **kwargs)
def bitswap_unwant(self, key, **kwargs):
"""
Remove a given block from wantlist.
Parameters
----------
key : str
Key to remove from wantlist.
"""
args = (key,)
return self._client.request('/bitswap/unwant', args, **kwargs)
def object_data(self, multihash, **kwargs):
r"""Returns the raw bytes in an IPFS object.
.. code-block:: python
>>> c.object_data('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
b'\x08\x01'
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
str : Raw object data
"""
args = (multihash,)
return self._client.request('/object/data', args, **kwargs)
def object_new(self, template=None, **kwargs):
"""Creates a new object from an IPFS template.
By default this creates and returns a new empty merkledag node, but you
may pass an optional template argument to create a preformatted node.
.. code-block:: python
>>> c.object_new()
{'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'}
Parameters
----------
template : str
Blueprints from which to construct the new object. Possible values:
* ``"unixfs-dir"``
* ``None``
Returns
-------
dict : Object hash
"""
args = (template,) if template is not None else ()
return self._client.request('/object/new', args,
decoder='json', **kwargs)
def object_links(self, multihash, **kwargs):
"""Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object hash and merkedag links
"""
args = (multihash,)
return self._client.request('/object/links', args,
decoder='json', **kwargs)
def object_get(self, multihash, **kwargs):
"""Get and serialize the DAG node named by multihash.
.. code-block:: python
>>> c.object_get('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Data': '\x08\x01',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 174},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1474},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version', 'Size': 55}]}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict : Object data and links
"""
args = (multihash,)
return self._client.request('/object/get', args,
decoder='json', **kwargs)
def object_put(self, file, **kwargs):
"""Stores input as a DAG object and returns its key.
.. code-block:: python
>>> c.object_put(io.BytesIO(b'''
... {
... "Data": "another",
... "Links": [ {
... "Name": "some link",
... "Hash": "QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCV … R39V",
... "Size": 8
... } ]
... }'''))
{'Hash': 'QmZZmY4KCu9r3e7M2Pcn46Fc5qbn6NpzaAGaYb22kbfTqm',
'Links': [
{'Hash': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
'Size': 8, 'Name': 'some link'}
]
}
Parameters
----------
file : io.RawIOBase
(JSON) object from which the DAG object will be created
Returns
-------
dict : Hash and links of the created DAG object
See :meth:`~ipfsapi.Object.object_links`
"""
body, headers = multipart.stream_files(file, self.chunk_size)
return self._client.request('/object/put', decoder='json',
data=body, headers=headers, **kwargs)
def object_stat(self, multihash, **kwargs):
"""Get stats for the DAG node named by multihash.
.. code-block:: python
>>> c.object_stat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'LinksSize': 256, 'NumLinks': 5,
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'BlockSize': 258, 'CumulativeSize': 274169, 'DataSize': 2}
Parameters
----------
multihash : str
Key of the object to retrieve, in base58-encoded multihash format
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/object/stat', args,
decoder='json', **kwargs)
def object_patch_append_data(self, multihash, new_data, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have the provided data appended to it,
and will thus have a new Hash.
.. code-block:: python
>>> c.object_patch_append_data("QmZZmY … fTqm", io.BytesIO(b"bla"))
{'Hash': 'QmR79zQQj2aDfnrNgczUhvf2qWapEfQ82YQRt3QjrbhSb2'}
Parameters
----------
multihash : str
The hash of an ipfs object to modify
new_data : io.RawIOBase
The data to append to the object's data section
Returns
-------
dict : Hash of new object
"""
args = (multihash,)
body, headers = multipart.stream_files(new_data, self.chunk_size)
return self._client.request('/object/patch/append-data', args,
decoder='json',
data=body, headers=headers, **kwargs)
def object_patch_add_link(self, root, name, ref, create=False, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have a link to the provided object.
.. code-block:: python
>>> c.object_patch_add_link(
... 'QmR79zQQj2aDfnrNgczUhvf2qWapEfQ82YQRt3QjrbhSb2',
... 'Johnny',
... 'QmR79zQQj2aDfnrNgczUhvf2qWapEfQ82YQRt3QjrbhSb2'
... )
{'Hash': 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZKyj2x8Z3k'}
Parameters
----------
root : str
IPFS hash for the object being modified
name : str
name for the new link
ref : str
IPFS hash for the object being linked to
create : bool
Create intermediary nodes
Returns
-------
dict : Hash of new object
"""
kwargs.setdefault("opts", {"create": create})
args = ((root, name, ref),)
return self._client.request('/object/patch/add-link', args,
decoder='json', **kwargs)
def object_patch_rm_link(self, root, link, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will lack a link to the specified object.
.. code-block:: python
>>> c.object_patch_rm_link(
... 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZKyj2x8Z3k',
... 'Johnny'
... )
{'Hash': 'QmR79zQQj2aDfnrNgczUhvf2qWapEfQ82YQRt3QjrbhSb2'}
Parameters
----------
root : str
IPFS hash of the object to modify
link : str
name of the link to remove
Returns
-------
dict : Hash of new object
"""
args = ((root, link),)
return self._client.request('/object/patch/rm-link', args,
decoder='json', **kwargs)
def object_patch_set_data(self, root, data, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will have the same links as the old object but
with the provided data instead of the old object's data contents.
.. code-block:: python
>>> c.object_patch_set_data(
... 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZKyj2x8Z3k',
... io.BytesIO(b'bla')
... )
{'Hash': 'QmSw3k2qkv4ZPsbu9DVEJaTMszAQWNgM1FTFYpfZeNQWrd'}
Parameters
----------
root : str
IPFS hash of the object to modify
data : io.RawIOBase
The new data to store in root
Returns
-------
dict : Hash of new object
"""
args = (root,)
body, headers = multipart.stream_files(data, self.chunk_size)
return self._client.request('/object/patch/set-data', args,
decoder='json',
data=body, headers=headers, **kwargs)
def file_ls(self, multihash, **kwargs):
"""Lists directory contents for Unix filesystem objects.
The result contains size information. For files, the child size is the
total size of the file contents. For directories, the child size is the
IPFS link size.
The path can be a prefixless reference; in this case, it is assumed
that it is an ``/ipfs/`` reference and not ``/ipns/``.
.. code-block:: python
>>> c.file_ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D')
{'Arguments': {'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D':
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D'},
'Objects': {
'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D': {
'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Size': 0, 'Type': 'Directory',
'Links': [
{'Hash': 'Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV',
'Name': 'Makefile', 'Size': 163, 'Type': 'File'},
{'Hash': 'QmeKozNssnkJ4NcyRidYgDY2jfRZqVEoRGfipkgath71bX',
'Name': 'example', 'Size': 1463, 'Type': 'File'},
{'Hash': 'QmZAL3oHMQYqsV61tGvoAVtQLs1WzRe1zkkamv9qxqnDuK',
'Name': 'home', 'Size': 3947, 'Type': 'Directory'},
{'Hash': 'QmZNPyKVriMsZwJSNXeQtVQSNU4v4KEKGUQaMT61LPahso',
'Name': 'lib', 'Size': 268261, 'Type': 'Directory'},
{'Hash': 'QmSY8RfVntt3VdxWppv9w5hWgNrE31uctgTiYwKir8eXJY',
'Name': 'published-version',
'Size': 47, 'Type': 'File'}
]
}
}}
Parameters
----------
multihash : str
The path to the object(s) to list links from
Returns
-------
dict
"""
args = (multihash,)
return self._client.request('/file/ls', args, decoder='json', **kwargs)
def resolve(self, name, recursive=False, **kwargs):
"""Accepts an identifier and resolves it to the referenced item.
There are a number of mutable name protocols that can link among
themselves and into IPNS. For example IPNS references can (currently)
point at an IPFS object, and DNS links can point at other DNS links,
IPNS entries, or IPFS objects. This command accepts any of these
identifiers.
.. code-block:: python
>>> c.resolve("/ipfs/QmTkzDwWqPbnAh5YiV5VwcTLnGdw … ca7D/Makefile")
{'Path': '/ipfs/Qmd2xkBfEwEs9oMTk77A6jrsgurpF3ugXSg7dtPNFkcNMV'}
>>> c.resolve("/ipns/ipfs.io")
{'Path': '/ipfs/QmTzQ1JRkWErjk39mryYw2WVaphAZNAREyMchXzYQ7c15n'}
Parameters
----------
name : str
The name to resolve
recursive : bool
Resolve until the result is an IPFS name
Returns
-------
dict : IPFS path of resource
"""
kwargs.setdefault("opts", {"recursive": recursive})
args = (name,)
return self._client.request('/resolve', args, decoder='json', **kwargs)
def key_list(self, **kwargs):
"""Returns a list of generated public keys that can be used with name_publish
.. code-block:: python
>>> c.key_list()
[{'Name': 'self',
'Id': 'QmQf22bZar3WKmojipms22PkXH1MZGmvsqzQtuSvQE3uhm'},
{'Name': 'example_key_name',
'Id': 'QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8'}
]
Returns
-------
list : List of dictionaries with Names and Ids of public keys.
"""
return self._client.request('/key/list', decoder='json', **kwargs)
def key_gen(self, key_name, type, size=2048, **kwargs):
"""Adds a new public key that can be used for name_publish.
.. code-block:: python
>>> c.key_gen('example_key_name')
{'Name': 'example_key_name',
'Id': 'QmQLaT5ZrCfSkXTH6rUKtVidcxj8jrW3X2h75Lug1AV7g8'}
Parameters
----------
key_name : str
Name of the new Key to be generated. Used to reference the Keys.
type : str
Type of key to generate. The current possible keys types are:
* ``"rsa"``
* ``"ed25519"``
size : int
Bitsize of key to generate
Returns
-------
dict : Key name and Key Id
"""
opts = {"type": type, "size": size}
kwargs.setdefault("opts", opts)
args = (key_name,)
return self._client.request('/key/gen', args,
decoder='json', **kwargs)
def key_rm(self, key_name, *key_names, **kwargs):
"""Remove a keypair
.. code-block:: python
>>> c.key_rm("bla")
{"Keys": [
{"Name": "bla",
"Id": "QmfJpR6paB6h891y7SYXGe6gapyNgepBeAYMbyejWA4FWA"}
]}
Parameters
----------
key_name : str
Name of the key(s) to remove.
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name,) + key_names
return self._client.request('/key/rm', args, decoder='json', **kwargs)
def key_rename(self, key_name, new_key_name, **kwargs):
"""Rename a keypair
.. code-block:: python
>>> c.key_rename("bla", "personal")
{"Was": "bla",
"Now": "personal",
"Id": "QmeyrRNxXaasZaoDXcCZgryoBCga9shaHQ4suHAYXbNZF3",
"Overwrite": False}
Parameters
----------
key_name : str
Current name of the key to rename
new_key_name : str
New name of the key
Returns
-------
dict : List of key names and IDs that have been removed
"""
args = (key_name, new_key_name)
return self._client.request('/key/rename', args, decoder='json',
**kwargs)
def name_publish(self, ipfs_path, resolve=True, lifetime="24h", ttl=None,
key=None, **kwargs):
"""Publishes an object to IPNS.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In publish, the
default value of *name* is your own identity public key.
.. code-block:: python
>>> c.name_publish('/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZK … GZ5d')
{'Value': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d',
'Name': 'QmVgNoP89mzpgEAAqK8owYoDEyB97MkcGvoWZir8otE9Uc'}
Parameters
----------
ipfs_path : str
IPFS path of the object to be published
resolve : bool
Resolve given path before publishing
lifetime : str
Time duration that the record will be valid for
Accepts durations such as ``"300s"``, ``"1.5h"`` or ``"2h45m"``.
Valid units are:
* ``"ns"``
* ``"us"`` (or ``"µs"``)
* ``"ms"``
* ``"s"``
* ``"m"``
* ``"h"``
ttl : int
Time duration this record should be cached for
key : string
Name of the key to be used, as listed by 'ipfs key list'.
Returns
-------
dict : IPNS hash and the IPFS path it points at
"""
opts = {"lifetime": lifetime, "resolve": resolve}
if ttl:
opts["ttl"] = ttl
if key:
opts["key"] = key
kwargs.setdefault("opts", opts)
args = (ipfs_path,)
return self._client.request('/name/publish', args,
decoder='json', **kwargs)
def name_resolve(self, name=None, recursive=False,
nocache=False, **kwargs):
"""Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is your own identity public key.
.. code-block:: python
>>> c.name_resolve()
{'Path': '/ipfs/QmfZY61ukoQuCX8e5Pt7v8pRfhkyxwZKZMTodAtmvyGZ5d'}
Parameters
----------
name : str
The IPNS name to resolve (defaults to the connected node)
recursive : bool
Resolve until the result is not an IPFS name (default: false)
nocache : bool
Do not use cached entries (default: false)
Returns
-------
dict : The IPFS path the IPNS hash points at
"""
kwargs.setdefault("opts", {"recursive": recursive,
"nocache": nocache})
args = (name,) if name is not None else ()
return self._client.request('/name/resolve', args,
decoder='json', **kwargs)
def dns(self, domain_name, recursive=False, **kwargs):
"""Resolves DNS links to the referenced object.
Multihashes are hard to remember, but domain names are usually easy to
remember. To create memorable aliases for multihashes, DNS TXT records
can point to other DNS links, IPFS objects, IPNS keys, etc.
This command resolves those links to the referenced object.
For example, with this DNS TXT record::