'How to implement merkle hash tree in python
Running my code it keeps giving me an error:
File "C:\Users\Joshua Ajogu Alfa\Desktop\merklehashtreebuild1.py", line 36, in inputString = sys.argv[1] IndexError: list index out of range
#!/usr/bin/python
import hashlib,sys
class MerkleTreeNode:
def __init__(self,value):
self.left = None
self.right = None
self.value = value
self.hashValue = hashlib.sha256(value.encode('utf-8')).hexdigest()
def buildTree(leaves,f):
nodes = []
for i in leaves:
nodes.append(MerkleTreeNode(i))
while len(nodes)!=1:
temp = []
for i in range(0,len(nodes),2):
node1 = nodes[i]
if i+1 < len(nodes):
node2 = nodes[i+1]
else:
temp.append(nodes[i])
break
f.write("Left child : "+ node1.value + " | Hash : " + node1.hashValue +" \n")
f.write("Right child : "+ node2.value + " | Hash : " + node2.hashValue +" \n")
concatenatedHash = node1.hashValue + node2.hashValue
parent = MerkleTreeNode(concatenatedHash)
parent.left = node1
parent.right = node2
f.write("Parent(concatenation of "+ node1.value + " and " + node2.value + ") : " +parent.value + " | Hash : " + parent.hashValue +" \n")
temp.append(parent)
nodes = temp
return nodes[0]
inputString = sys.argv[1]
leavesString = inputString[1:len(inputString)-1]
leaves = leavesString.split(",")
f = open("merkle.tree", "w")
root = buildTree(leaves,f)
f.close()
Solution 1:[1]
You can call the program with arguments like this:
python program.py something another
Also I think adding a except block or checking the length of arguments before is better:
try:
inputString = sys.argv[1]
except IndexError:
pass # <- do something if there's no argument
## OR
if len(sys.argv) > 1:
inputString = sys.argv[1]
else:
pass # <- do something
Solution 2:[2]
The error description
Hi there. The error you've got tells you that, at execution time, the program couldn't find any value at position 1 in the arguments list.
A generic solution
As written in the Python 3.10 official documentation you can run a example.py Python script on Windows using the command py example.py
. You can then add arguments like in the command written below.
py example.py argument1 argument2 ... argumentN
An example
If you want to run the example.py python script on Windows passing the arguments jack
, oliver
and 134
you'll have to run the python script using the command below.
py example.py jack oliver 134
Referring to the official python docs for sys library, launching the script as written above you will be able to access to that arguments using sys.argv
List, for example:
import sys
sys.argv[0] # example.py
sys.argv[1] # jack
sys.argv[2] # oliver
sys.argv[3] # 134
Solution 3:[3]
you aren't passing the arguments to the file while starting it, do it in this way:
python C:/path/to/your/python/file.py arg1 arg2 arg3 argn ...
to avoid any error consider to do:
try:
inputString = sys.argv[1]
except ValueError:
inputstring = input("please add your input string: ")
# do anything you want if you dislike this
Note: remember that you always have a sys.argv list that contains only the filename [main.py]
Solution 4:[4]
sys.argv is set by the command you run (i'll treat windows since it's your situation)
maybe trying to run a small program like this one will help
import sys
print(*sys.argv)
the rule of argv
is that the first argument (sys.arg[0]
) is the name of your program as you writen it in the CLI and the next are strings that contains each arguments you passed so running:
python prog.py 2 arg1 arg2
will set argv at :
["prog.py", "2", "arg1", "arg2"]
normaly a whitespace separate argument but you can use double quote to ignore them.
running:
python prog.py 1 "arg1 arg2"
will set argv at :
["prog.py", "2", "arg1 arg2"]
in your case it look like you are not giving any argument to your program since argv[1]
does not exist.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Marte Valerio Falcone |
Solution 3 | |
Solution 4 | LTBS46 |