from getEthAddresses import getIPs,getEthereumAddresses
from web3 import Web3
from web3.auto import w3
from extractPriv import extractPrivAddress
from smartContract import smartContract
import time
import sqlite3
from sqlite3 import Error
import os

#connect to db
def create_connection(db_file):
	conn = None
	try:
		conn = sqlite3.connect(db_file)
	except Error as e:
		print(e)
	return conn

#get data from db
def select_data(conn):
	cur = conn.cursor()
	cur.execute("SELECT * FROM Addresses")
	rows = cur.fetchall()
	cur.close()
	return rows

#update IP address
def update_data(conn,ip,eth):
	try:
		cur = conn.cursor()
		cur.execute("UPDATE Addresses SET IP=? WHERE EthAddress=? ",(ip,eth))
		print("IP successfully updated")
		conn.commit()
		cur.close()
	except Error as e:
		print(e)

	cur.close()

#main function
while True:
	#get IP addresses connected to machine 
	IPlist = getIPs()
	#get ethereum addresses from genesis block
	EthList = getEthereumAddresses()
	#get registered ethereum addresses and IPs from database
	db_read = select_data(create_connection(r"/home/nicoski/Desktop/dockChain/files/permitted.db")) 
	#compare addresses with database results
	for ip in IPlist:
		for index in enumerate(db_read):
			for ipaddr in enumerate(index):
				if ip != ipaddr:
					verified = False
					counter = 0
					while verified == False:
						try:
							verify = str(input("Enter your ETH address: "))
							if verify in EthList:
								newIP = input("Enter your machine's current IP: ")
								update_data(create_connection(r"/home/nicoski/Desktop/dockChain/files/permitted.db"),newIP,verify)
								verified = True
								break
							else:
								print("Verification failed")
								counter = counter + 1
								if counter >= 3:
									os.system('iptables -A INPUT -s {0} -j DROP'.format(ip))
									print("Connection closed")
									verified = True
						except:
							counter = counter + 1
							if counter >= 3:
								os.system('iptables -A INPUT -s {0} -j DROP'.format(ip))
								verified = True
							if verified == True:
								break
				if verified == True:
					break
			if verified == True:
				break
		if verified == True:
			break
	time.sleep(10) #sleep for 10 seconds
