-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpublishIP.py
More file actions
127 lines (107 loc) · 4.75 KB
/
publishIP.py
File metadata and controls
127 lines (107 loc) · 4.75 KB
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
import os
import requests
import subprocess
import json
import time
import sys
from datetime import datetime, timezone
IPFS_API_URL = os.environ.get('NINJADOH_IPFS_API_URL', 'http://127.0.0.1:5001/api/v0')
# IPNS key ID for pubsub (set NINJADOH_IPNS_NAME; generate with: ipfs key gen ninjadoh)
IPNS_NAME = os.environ.get('NINJADOH_IPNS_NAME')
def post_ip_to_ipfs(ip_address):
# Get the current timestamp with timezone awareness
timestamp = datetime.now(timezone.utc).isoformat() # UTC timestamp in ISO 8601 format
# Create content for IPFS including the IP address and timestamp
content = {
'ip': ip_address,
'query_path': f"/{IPNS_NAME}",
'timestamp': timestamp
}
content_json = json.dumps(content)
# Add content to IPFS
response = requests.post(f"{IPFS_API_URL}/add", files={'file': ('content.json', content_json)})
response.raise_for_status() # Raise an exception for HTTP errors
cid = response.json()['Hash']
print(f"Added content to IPFS with CID: {cid}")
# Pin the content to your local IPFS node
pin_response = requests.post(f"{IPFS_API_URL}/pin/add?arg={cid}")
pin_response.raise_for_status()
print(f"Pinned CID: {cid}")
# Add the content to MFS so it shows up in the Files section
add_to_mfs(cid, "/posted_ip.json") # You can specify the path inside MFS
return cid
def add_to_mfs(cid, mfs_path):
# Remove the file from MFS if it already exists
try:
rm_response = requests.post(f"{IPFS_API_URL}/files/rm?arg={mfs_path}&force=true")
if rm_response.status_code == 200:
print(f"Removed existing file at {mfs_path} in MFS")
except requests.exceptions.HTTPError as e:
# Ignore the error if the file does not exist
if e.response.status_code != 404:
raise
# Add the CID to MFS so it appears in the Files section
mfs_response = requests.post(f"{IPFS_API_URL}/files/cp?arg=/ipfs/{cid}&arg={mfs_path}")
mfs_response.raise_for_status()
print(f"Added CID to MFS at {mfs_path}")
def publish_to_ipns(cid, key_name='self'):
# Publish the CID to IPNS using the HTTP API with forced update
publish_url = f"{IPFS_API_URL}/name/publish"
params = {
'arg': f'/ipfs/{cid}', # Path to the content
'key': key_name, # Key name (default is 'self')
'allow-offline': True, # Allow publishing even if offline (forces update)
'lifetime': '24h', # Set the IPNS record's lifetime
'ttl': '1m', # Set TTL to ensure quicker cache expiration
'resolve': True # Resolve before publishing to ensure correct CID
}
response = requests.post(publish_url, params=params)
response.raise_for_status() # Raise an exception for HTTP errors
ipns_hash = response.json().get('Name')
print(f"Published to IPNS: {ipns_hash} with CID: {cid}")
# Verify the new CID
time.sleep(5) # Wait briefly for the IPNS update to propagate
resolve_ipns(ipns_hash)
# Manually call pubsub with the new CID
pubsub_publish(cid)
def pubsub_publish(cid):
if not IPNS_NAME:
raise ValueError(
'NINJADOH_IPNS_NAME must be set to your IPNS key ID. '
'Generate with: ipfs key gen ninjadoh, then set the env var to the key ID.'
)
# Publish the new CID to the pubsub topic using subprocess
pubsub_topic = f"/ipns/{IPNS_NAME}"
pubsub_message = f"New CID: {cid}"
try:
# Create a temporary file with the pubsub message content
with open("cid_message.txt", "w") as f:
f.write(pubsub_message)
# Call the IPFS pubsub pub command with subprocess
subprocess.run(
['ipfs', 'pubsub', 'pub', pubsub_topic, 'cid_message.txt'],
check=True
)
print(f"Published {pubsub_message} to pubsub topic {pubsub_topic}")
except subprocess.CalledProcessError as e:
print(f"Failed to publish to pubsub: {e}")
finally:
# Clean up the temporary file
try:
subprocess.run(['rm', 'cid_message.txt'], check=True)
except Exception as cleanup_err:
print(f"Failed to remove temporary file: {cleanup_err}")
def resolve_ipns(ipns_hash):
resolve_url = f"{IPFS_API_URL}/name/resolve?arg=/ipns/{ipns_hash}&nocache=true"
response = requests.post(resolve_url)
response.raise_for_status()
resolved_cid = response.json().get('Path')
print(f"Resolved IPNS to CID: {resolved_cid}")
if __name__ == "__main__":
# Accept the IP address as a command-line argument
if len(sys.argv) < 2:
print("Usage: python publishIP.py <IP_ADDRESS>")
sys.exit(1)
ip_address = sys.argv[1] # Get the IP address from command-line arguments
cid = post_ip_to_ipfs(ip_address)
publish_to_ipns(cid)