ipfs-node 0.1.12rc2__py3-none-android_28_arm64_v8a.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ import ctypes
2
+ import json
3
+ from typing import List, Dict, Optional, Tuple, Any, Union
4
+ from ipfs_tk_generics.tunnels import SenderTunnel, ListenerTunnel, TunnelsList, BaseTunnels
5
+ from libkubo import libkubo, c_str, from_c_str, ffi, c_bool
6
+
7
+
8
+
9
+
10
+
11
+ class NodeTunnels(BaseTunnels):
12
+ """
13
+ Provides P2P stream mounting functionality for IPFS nodes.
14
+
15
+ Stream mounting allows you to expose local TCP services to the libp2p network
16
+ and connect to remote TCP services exposed by other nodes.
17
+ """
18
+
19
+ def __init__(self, node):
20
+ self._node = node
21
+ self._repo_path = self._node._repo_path
22
+ BaseTunnels.__init__(self)
23
+
24
+
25
+ def _enable_p2p(self) -> bool:
26
+ """Enable p2p functionality in the IPFS configuration."""
27
+
28
+ repo_path = c_str(self._repo_path.encode('utf-8'))
29
+ result = libkubo.P2PEnable(repo_path)
30
+
31
+ if result <= 0:
32
+ print(f"Warning: Could not enable p2p functionality ({result})")
33
+ return False
34
+ return True
35
+
36
+ def open_sender(self, name: str, listen_addr: int | str, target_peer_id: str):
37
+ """
38
+ Forward local connections to a remote peer.
39
+
40
+ This creates a new listener that forwards connections to the specified
41
+ peer over the libp2p network.
42
+
43
+ Args:
44
+ name: The protocol name to use for the forwarding.
45
+ listen_addr: The local address to listen on (e.g. "127.0.0.1:8080").
46
+ target_peer_id: The peer ID to forward connections to.
47
+
48
+ Returns:
49
+ bool: True if the forwarding was set up successfully, False otherwise.
50
+ """
51
+ # if not target_peer_id.startswith("/p2p/"):
52
+ # target_peer_id = f"/p2p/{target_peer_id}"
53
+ result = libkubo.P2PForward(
54
+ c_str(self._repo_path.encode('utf-8')),
55
+ c_str(name.encode('utf-8')),
56
+ c_str(self._port_to_addr(listen_addr).encode('utf-8')),
57
+ c_str(target_peer_id.encode('utf-8'))
58
+ )
59
+ if result > 0:
60
+ return
61
+ if result == -2:
62
+ print(f"Can't create sender {name} {listen_addr} {target_peer_id}")
63
+ raise Exception("IpfsNode.tunnels.open_sender: failed to open sender: bind: address already in use")
64
+
65
+
66
+ raise Exception("IpfsNode.tunnels.open_sender: failed to open sender")
67
+
68
+ def open_listener(self, name: str, target_addr: int | str):
69
+ """
70
+ Listen for libp2p connections and forward them to a local TCP service.
71
+
72
+ This exposes a local TCP service to the libp2p network.
73
+
74
+ Args:
75
+ name: The protocol name to use for the listener.
76
+ target_addr: The local address to forward connections to (e.g. "127.0.0.1:8080").
77
+
78
+ Returns:
79
+ bool: True if the listener was set up successfully, False otherwise.
80
+ """
81
+ result = libkubo.P2PListen(
82
+ c_str(self._repo_path.encode('utf-8')),
83
+ c_str(name.encode('utf-8')),
84
+ c_str(self._port_to_addr(target_addr)))
85
+ if result > 0:
86
+ return
87
+ if result == -2:
88
+ print(f"Can't open listener {name} {target_addr}")
89
+ raise Exception("IpfsNode.tunnels.open_sender: failed to open listener")
90
+
91
+
92
+ raise Exception("IpfsNode.tunnels.open_sender: failed to open listener")
93
+
94
+ def close_sender(self, name: str = None, port: int = None, peer_id: str = None) -> int:
95
+ """
96
+ Close a specific TCP forwarding connection, optionally filtered by protocol, port, or peer ID.
97
+
98
+ Args:
99
+ name: Optional protocol filter
100
+ port: Optional port filter
101
+ peer_id: Optional peer ID filter
102
+
103
+ Returns:
104
+ int: Number of forwarding connections closed
105
+ """
106
+ if peer_id and not peer_id.startswith("/p2p/"):
107
+ peer_id = f"/p2p/{peer_id}"
108
+ return self.close_tcp_connections(name, port, peer_id, senders=True, listeners=False)
109
+
110
+ def close_listener(self, name: str = None, port: int = None) -> int:
111
+ """
112
+ Close a specific TCP listening connection, optionally filtered by protocol name or port.
113
+
114
+ Args:
115
+ name: Optional protocol name filter
116
+ port: Optional port filter
117
+
118
+ Returns:
119
+ int: Number of listening connections closed
120
+ """
121
+ return self.close_tcp_connections(name, target_addr=port, listeners=True, senders=False)
122
+
123
+ def close_streams(self, name: str, port: int | None = None, target_peer_id: str = "") -> bool:
124
+ """
125
+ Close a P2P listener or stream.
126
+
127
+ Args:
128
+ name: The protocol name of the listener or stream to close.
129
+ listen_addr: For streams, the local address that the stream listens on.
130
+ target_peer_id: For streams, the peer ID that the stream connects to.
131
+
132
+ Returns:
133
+ bool: True if the listener or stream was closed successfully, False otherwise.
134
+ """
135
+ result = libkubo.P2PClose(
136
+ c_str(self._repo_path.encode('utf-8')),
137
+ c_str(name.encode('utf-8')),
138
+ c_str(self._port_to_addr(port)) if port else c_str(""),
139
+ c_str(target_peer_id.encode('utf-8'))
140
+ )
141
+ return result > 0
142
+
143
+ def close_tcp_connections(
144
+ self,
145
+ name: str = "", listen_addr: str | int | None = None, target_addr: str | int | None = None, all: bool = False,
146
+ listeners: bool = True, senders: bool = True
147
+ ) -> int:
148
+ """
149
+ Close specific TCP p2p connections, optionally filtered by protocol name, port, or peer ID.
150
+
151
+ Args:
152
+ name: Optional protocol name filter
153
+ port: Optional port filter
154
+ peer_id: Optional peer ID filter
155
+
156
+ Returns:
157
+ int: Number of connections closed
158
+ """
159
+
160
+ repo_path = c_str(self._repo_path.encode('utf-8'))
161
+
162
+ result = libkubo.P2PClose(
163
+ repo_path, c_str(name),
164
+ c_str(self._port_to_addr(listen_addr)),
165
+ c_str(self._port_to_addr(target_addr)),
166
+ c_bool(all), c_bool(listeners), c_bool(senders)
167
+ )
168
+ return result
169
+
170
+ def close_all_senders(self) -> int:
171
+ """
172
+ Close all TCP forwarding connections.
173
+
174
+ Returns:
175
+ int: Number of forwarding connections closed
176
+ """
177
+ return self.close_tcp_connections(all=True, listeners=False, senders=True)
178
+
179
+ def close_all_listeners(self) -> int:
180
+ """
181
+ Close all TCP listening connections.
182
+
183
+ Returns:
184
+ int: Number of listening connections closed
185
+ """
186
+ return self.close_tcp_connections(all=True, listeners=True, senders=False)
187
+ def close_all(self) -> int:
188
+ """
189
+ Close all TCP connections.
190
+
191
+ Returns:
192
+ int: Number of listening connections closed
193
+ """
194
+ return self.close_tcp_connections(all=True, listeners=True, senders=True)
195
+
196
+ def get_tunnels(self) ->TunnelsList:
197
+ """
198
+ List all active P2P tunnels.
199
+ """
200
+ result_ptr = libkubo.P2PListListeners(
201
+ c_str(self._repo_path.encode('utf-8'))
202
+ )
203
+
204
+ if not result_ptr:
205
+ return [], []
206
+
207
+ # Convert the C string to a Python string and release memory
208
+ result_str = from_c_str(result_ptr)
209
+ # libkubo.free(result_ptr)
210
+
211
+ if not result_str:
212
+ return [], []
213
+
214
+ # Parse the JSON
215
+ try:
216
+ result = json.loads(result_str)
217
+ except json.JSONDecodeError:
218
+ return [], []
219
+
220
+ # Add local listeners
221
+ listeners = []
222
+ for item in result.get('Listens', []):
223
+ listener = ListenerTunnel(
224
+ name=item.get('Protocol', ''),
225
+ # listen_address=item.get('ListenAddress', ''),
226
+ target_address=item.get('TargetAddress', '')
227
+ )
228
+ listeners.append(listener)
229
+
230
+ # Add remote listeners
231
+ forwarders = []
232
+ for item in result.get('Forwards', []):
233
+ listener = SenderTunnel(
234
+ name=item.get('Protocol', ''),
235
+ listen_address=item.get('ListenAddress', ''),
236
+ target_address=item.get('TargetAddress', '')
237
+ )
238
+ forwarders.append(listener)
239
+
240
+ # # Extract active streams
241
+ # streams = []
242
+ # for item in result.get('Streams', []):
243
+ # stream = P2PStream(
244
+ # name=item.get('Protocol', ''),
245
+ # origin_address=item.get('LocalAddr', ''),
246
+ # target_address=item.get('RemoteAddr', '')
247
+ # )
248
+ # streams.append(stream)
249
+
250
+ return TunnelsList(senders=forwarders, listeners=listeners)
251
+
252
+
253
+ def _port_to_addr(self, addr: int | str | None) -> str:
254
+ if not addr:
255
+ return ""
256
+ if isinstance(addr, int):
257
+ return f"/ip4/{self._node._ipfs_host_ip()}/tcp/{addr}"
258
+ else:
259
+ return addr
260
+ def terminate(self):
261
+ pass
262
+ def __del__(self):
263
+ self.terminate()
@@ -0,0 +1,3 @@
1
+ """Utility functions for the Kubo Python library."""
2
+
3
+ __all__ = ["cid_utils", "peer_utils"]
@@ -0,0 +1,55 @@
1
+ """
2
+ Utilities for working with IPFS Content Identifiers (CIDs).
3
+ """
4
+
5
+ import re
6
+
7
+ # Regular expression for matching CID v0 (Qm...)
8
+ CID_V0_REGEX = re.compile(r"^Qm[1-9A-Za-z]{44}$")
9
+
10
+ # Regular expression for matching CID v1
11
+ CID_V1_REGEX = re.compile(r"^ba[a-zA-Z2-7]{57}$")
12
+
13
+ def is_valid_cid(cid: str) -> bool:
14
+ """
15
+ Check if a string is a valid IPFS CID.
16
+
17
+ Args:
18
+ cid: The Content Identifier to check.
19
+
20
+ Returns:
21
+ bool: True if the CID is valid, False otherwise.
22
+ """
23
+ if not cid or not isinstance(cid, str):
24
+ return False
25
+
26
+ # Check for CID v0 (starts with "Qm" and is 46 characters long)
27
+ if CID_V0_REGEX.match(cid):
28
+ return True
29
+
30
+ # Check for CID v1 (starts with "ba" and is 59 characters long)
31
+ if CID_V1_REGEX.match(cid):
32
+ return True
33
+
34
+ # Could add more sophisticated validation here
35
+ return False
36
+
37
+ def format_cid_link(cid: str, gateway: str = "https://ipfs.io/ipfs/") -> str:
38
+ """
39
+ Format a CID as a link through an IPFS gateway.
40
+
41
+ Args:
42
+ cid: The Content Identifier.
43
+ gateway: The IPFS gateway URL. Defaults to the public ipfs.io gateway.
44
+
45
+ Returns:
46
+ str: The gateway URL for the CID.
47
+ """
48
+ if not is_valid_cid(cid):
49
+ raise ValueError(f"Invalid CID: {cid}")
50
+
51
+ # Ensure the gateway URL ends with a slash
52
+ if not gateway.endswith("/"):
53
+ gateway += "/"
54
+
55
+ return f"{gateway}{cid}"
@@ -0,0 +1,62 @@
1
+ """
2
+ Utilities for working with IPFS peer addresses and connections.
3
+ """
4
+
5
+ import re
6
+
7
+ # Regular expression for matching multiaddress format
8
+ MULTIADDR_REGEX = re.compile(r"^(/[^/]+)+$")
9
+
10
+ # Regular expression for matching peer ID format (with multiaddress)
11
+ PEER_ID_REGEX = re.compile(r"/p2p/([a-zA-Z0-9]+)$")
12
+
13
+ def is_valid_multiaddr(addr: str) -> bool:
14
+ """
15
+ Check if a string is a valid IPFS multiaddress.
16
+
17
+ Args:
18
+ addr: The multiaddress to check.
19
+
20
+ Returns:
21
+ bool: True if the multiaddress is valid, False otherwise.
22
+ """
23
+ if not addr or not isinstance(addr, str):
24
+ return False
25
+
26
+ # Basic check for multiaddress format
27
+ return bool(MULTIADDR_REGEX.match(addr))
28
+
29
+ def extract_peer_id(multiaddr: str) -> str:
30
+ """
31
+ Extract the peer ID from a multiaddress.
32
+
33
+ Args:
34
+ multiaddr: The multiaddress containing a peer ID.
35
+
36
+ Returns:
37
+ str: The peer ID, or an empty string if not found.
38
+ """
39
+ if not is_valid_multiaddr(multiaddr):
40
+ return ""
41
+
42
+ # Find the peer ID component
43
+ match = PEER_ID_REGEX.search(multiaddr)
44
+ if match:
45
+ return match.group(1)
46
+
47
+ return ""
48
+
49
+ def get_bootstrap_peers() -> list:
50
+ """
51
+ Get a list of default IPFS bootstrap peers.
52
+
53
+ Returns:
54
+ list: A list of multiaddresses for the default bootstrap peers.
55
+ """
56
+ return [
57
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
58
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
59
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb",
60
+ "/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
61
+ "/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
62
+ ]
@@ -0,0 +1,18 @@
1
+ MIT No Attribution
2
+
3
+ Copyright [year] [fullname]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.