-
Notifications
You must be signed in to change notification settings - Fork 0
/
BitcoinCore
372 lines (285 loc) · 12 KB
/
BitcoinCore
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
#!/usr/bin/env python3
import os
import wget
import tarfile
import subprocess
import time
import sys
def create_downloads_directory():
downloads_directory = os.path.join(os.path.expanduser('~'), 'Downloads')
if not os.path.exists(downloads_directory):
os.makedirs(downloads_directory)
# Call the function to create the Downloads directory if it doesn't exist
create_downloads_directory()
url = "https://bitcoincore.org/bin/bitcoin-core-26.0/bitcoin-26.0-x86_64-linux-gnu.tar.gz"
download_command = f'wget {url} -P ~/Downloads'
try:
subprocess.run(download_command, shell=True, check=True)
print("Download completed successfully.")
except subprocess.CalledProcessError as e:
print(f"Error during download: {e}")
except Exception as e:
print(f"Download failed: {str(e)}")
filename = "bitcoin-26.0-x86_64-linux-gnu.tar.gz"
download_path = os.path.expanduser(f'~/Downloads/{filename}')
extracted_dir_parent = os.path.expanduser(f'~/Downloads')
try:
with tarfile.open(download_path, 'r:gz') as tar:
tar.extractall(path=extracted_dir_parent)
print(f"Extracted contents from '{filename}' into '{extracted_dir_parent}' successfully.")
except Exception as e:
print(f"Extraction failed: {str(e)}")
# Define the command to execute
command = "sudo install -m 0755 -o root -g root -t /usr/local/bin ~/Downloads/bitcoin-26.0/bin/*"
try:
# Get the full path to the Downloads directory
downloads_directory = os.path.expanduser('~/Downloads')
# Execute the command using subprocess and specify the working directory as the Downloads directory
subprocess.run(command, shell=True, check=True, cwd=downloads_directory)
print("Installation successful.")
except subprocess.CalledProcessError as e:
print(f"Error during installation: {e}")
except Exception as e:
print(f"An error occurred: {e}")
try:
# Start bitcoind in the background with the -daemon flag
subprocess.Popen(['bitcoind', '-daemon'])
print('Bitcoin Core (bitcoind) is starting in the background.')
except Exception as e:
print(f'An error occurred: {e}')
# Set the duration of the timer in seconds
duration = 5
print(f"Starting {duration}-second timer...")
# Sleep for the specified duration
time.sleep(duration)
print("Timer finished!")
def stop_bitcoincore():
"""Stops Bitcoin Core."""
command = "bitcoin-cli stop"
process = subprocess.Popen(command, shell=True)
process.wait()
if __name__ == "__main__":
stop_bitcoincore()
def create_bitcoin_conf_file():
"""Creates a bitcoin.conf file in the ~/.bitcoin directory."""
bitcoin_conf_filepath = os.path.join(os.path.expanduser('~'), '.bitcoin', 'bitcoin.conf')
if not os.path.exists(bitcoin_conf_filepath):
with open(bitcoin_conf_filepath, 'w') as f:
f.write('server=1\n')
f.write('txindex=1\n')
f.write('daemon=1\n')
f.write('rpcport=8332\n')
f.write('rpcbind=0.0.0.0\n')
f.write('rpcallowip=127.0.0.1\n')
f.write('rpcallowip=10.0.0.0/8\n')
f.write('rpcallowip=172.0.0.0/8\n')
f.write('rpcallowip=192.0.0.0/8\n')
f.write('zmqpubrawblock=tcp://0.0.0.0:28332\n')
f.write('zmqpubrawtx=tcp://0.0.0.0:28333\n')
f.write('zmqpubhashblock=tcp://0.0.0.0:28334\n')
f.write('whitelist=127.0.0.1\n')
if __name__ == '__main__':
create_bitcoin_conf_file()
def download_file(url, filename):
"""Downloads a file from the specified URL to the specified filename."""
downloads_directory = os.path.join(os.path.expanduser('~'), 'Downloads')
filepath = os.path.join(downloads_directory, filename)
print('Downloading file...')
if not os.path.exists(downloads_directory):
os.makedirs(downloads_directory)
wget.download(url, filepath)
# Set executable permission
os.chmod(filepath, 0o755) # Equivalent to chmod +x
# Example usage
url = "https://raw.githubusercontent.com/bitcoin/bitcoin/master/share/rpcauth/rpcauth.py"
filename = "rpcauth.py"
download_file(url, filename)
# Function to generate the rpcauth string
def run_rpcauth(username, password):
downloads_directory = os.path.join(os.path.expanduser('~'), 'Downloads')
script_path = os.path.join(downloads_directory, 'rpcauth.py')
command = [script_path, username, password]
result = subprocess.run(command, capture_output=True, text=True, check=True)
output = result.stdout.strip() # Remove leading/trailing whitespace
print("Script execution result:", output) # Added print statement to display the result
return output
# Function to append rpcauth to bitcoin.conf
def append_rpcauth_to_bitcoin_conf(rpcauth):
bitcoin_conf_path = os.path.join(os.path.expanduser('~'), '.bitcoin', 'bitcoin.conf')
with open(bitcoin_conf_path, 'a') as bitcoin_conf_file:
bitcoin_conf_file.write(f'{rpcauth}\n')
# Example usage
rpcusername = "rpc_username"
rpcpassword = "rpc_password"
rpcauth = run_rpcauth(rpcusername, rpcpassword)
append_rpcauth_to_bitcoin_conf(rpcauth)
# Define the path to the hidden file
file_path = os.path.expanduser("~/.Passwords")
# Check if the file already exists
if not os.path.exists(file_path):
# Create the file
with open(file_path, 'w') as password_file:
# Optionally, you can write some content to the file
password_file.write("This is a password file.\n")
password_file.write("You can store your passwords here.")
print(f"Created the file: {file_path}")
else:
print(f"The file already exists: {file_path}")
import re
# Specify the file path
file_path = "/home/humble/.bitcoin/bitcoin.conf"
# Read the content of the file
with open(file_path, 'r') as file:
original_config = file.read()
# Pattern to match the lines to be removed
pattern = re.compile(r'String to be appended to bitcoin.conf:[^\n]*\n|Your password:[^\n]*\n|rpc_password[^\n]*\n')
# Remove the matched pattern from the original configuration
modified_config = re.sub(pattern, '', original_config)
# Write the modified content back to the file
with open(file_path, 'w') as file:
file.write(modified_config)
print("File updated successfully.")
def main():
system_username = "humble"
create_bitcoind_service(system_username)
def create_bitcoind_service(system_username):
file_path = "/etc/systemd/system/bitcoind.service"
content = '''\
# It is not recommended to modify this file in-place, because it will
# be overwritten during package upgrades. If you want to add further
# options or overwrite existing ones then use
# $ systemctl edit bitcoind.service
# See "man systemd.service" for details.
# Note that almost all daemon options could be specified in
# /etc/bitcoin/bitcoin.conf, but keep in mind those explicitly
# specified as arguments in ExecStart= will override those in the
# config file.
[Unit]
Description=Bitcoin daemon
Documentation=https://github.com/bitcoin/bitcoin/blob/master/doc/init.md
# https://www.freedesktop.org/wiki/Software/systemd/NetworkTarget/
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/local/bin/bitcoind -pid=/run/bitcoind/bitcoind.pid \\
-conf=/home/{system_username}/.bitcoin/bitcoin.conf \\
-datadir=/home/{system_username}/.bitcoin \\
-startupnotify='systemd-notify --ready' \\
-shutdownnotify='systemd-notify --stopping'
# Make sure the config directory is readable by the service user
PermissionsStartOnly=true
#ExecStartPre=/bin/chgrp bitcoin /etc/bitcoin
# Process management
####################
Type=notify
NotifyAccess=all
PIDFile=/run/bitcoind/bitcoind.pid
Restart=on-failure
TimeoutStartSec=infinity
TimeoutStopSec=600
# Directory creation and permissions
####################################
# Run as bitcoin:bitcoin
User={system_username}
Group={system_username}
# /run/bitcoind
RuntimeDirectory=bitcoind
RuntimeDirectoryMode=0710
# /etc/bitcoin
ConfigurationDirectory=bitcoin
ConfigurationDirectoryMode=0710
# /var/lib/bitcoind
StateDirectory=bitcoind
StateDirectoryMode=0710
# Hardening measures
####################
# Provide a private /tmp and /var/tmp.
PrivateTmp=true
# Mount /usr, /boot/ and /etc read-only for the process.
ProtectSystem=full
# Deny access to /home, /root and /run/user
#ProtectHome=true
# Disallow the process and all of its children to gain
# new privileges through execve().
NoNewPrivileges=true
# Use a new /dev namespace only populated with API pseudo devices
# such as /dev/null, /dev/zero and /dev/random.
PrivateDevices=true
# Deny the creation of writable and executable memory mappings.
MemoryDenyWriteExecute=true
[Install]
WantedBy=multi-user.target
'''
# Write the content to a temporary file
temp_file_path = "/tmp/bitcoind.service"
with open(temp_file_path, 'w') as file:
file.write(content.format(system_username=system_username))
# Use sudo to move the temporary file to the target directory
move_command = ["sudo", "mv", temp_file_path, file_path]
subprocess.run(move_command, check=True)
# Set the correct ownership and permissions for the service file
chown_command = ["sudo", "chown", "root:root", file_path]
subprocess.run(chown_command, check=True)
chmod_command = ["sudo", "chmod", "644", file_path]
subprocess.run(chmod_command, check=True)
# Reload systemd configuration
reload_command = ["sudo", "systemctl", "daemon-reload"]
subprocess.run(reload_command, check=True)
# Enable the bitcoind service
enable_command = ["sudo", "systemctl", "enable", "bitcoind.service"]
subprocess.run(enable_command, check=True)
# Start the bitcoind service
start_command = ["sudo", "systemctl", "start", "bitcoind.service"]
subprocess.run(start_command, check=True)
if __name__ == "__main__":
main()
def main():
# Define the username directly in the script
username = "humble"
# Install Tor if not already installed
install_command = "sudo apt install tor"
subprocess.run(install_command, shell=True, check=True)
# Remove the existing torrc file with sudo permissions
remove_command = ["sudo", "rm", "/etc/tor/torrc"]
subprocess.run(remove_command, check=True)
# Create the new torrc file with the specified content
content = "\nControlPort 9051\nCookieAuthentication 1\nCookieAuthFileGroupReadable 1"
create_command = ["sudo", "bash", "-c", f'echo "{content}" > /etc/tor/torrc']
subprocess.run(create_command, check=True)
# Set the correct ownership and permissions for the file
chown_command = ["sudo", "chown", "root:root", "/etc/tor/torrc"]
subprocess.run(chown_command, check=True)
chmod_command = ["sudo", "chmod", "644", "/etc/tor/torrc"]
subprocess.run(chmod_command, check=True)
# Restart Tor with sudo permissions
restart_command = ["sudo", "systemctl", "restart", "tor"]
subprocess.run(restart_command, check=True)
if __name__ == "__main__":
main()
def main():
# Get the home directory path
home_dir = os.path.expanduser("~")
# Set the path to the bitcoin.conf file
bitcoin_conf_path = os.path.join(home_dir, ".bitcoin", "bitcoin.conf")
# Define the lines to be added
lines_to_add = [
"proxy=127.0.0.1:9050",
"listen=1",
"bind=127.0.0.1",
"onlynet=onion",
"addnode=g5bom63jg2brev2qzfrgazl4g6tnj6pb34noexewfge2vcqhcxl3t4yd.onion:8333"
]
# Open the bitcoin.conf file in append mode
with open(bitcoin_conf_path, "a") as conf_file:
# Add the lines to the file
for line in lines_to_add:
conf_file.write(line + "\n")
print("Lines added to bitcoin.conf successfully.")
if __name__ == "__main__":
main()
def restart_bitcoind():
# Restart bitcoind with sudo permissions
restart_command = ["sudo", "systemctl", "restart", "bitcoind"]
subprocess.run(restart_command, check=True)
if __name__ == "__main__":
restart_bitcoind()