Btmini
Btmini
Please vote for a candidate.
") return + Vot ingContract . deployed().then(function(instance){ 9Decentralized Voting System Using Ethereum Blockchain instance. vote(parseInt (candidateID)) .then(function(result){ $("#voteButton").attr("disabled", true); $("#tmsg") .htm1("Voted
"); window. location.reload(1); » })-catch(function(err){ console.error("ERROR! " + err.message) ») } + window. addEventListener("load", function() { if (typeof web3 ! ndefined") { console.warn("Using web3 detected from external source like Metamask" ) window.eth = new Neb3 (window. ethereum) } else { console.warn("No web3 detected. Falling back to http: //localhost:9545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for deployment. More info here: http: //truffleframework.com/tutorials/truffle-and-metamask") window.eth = new Web3(new Web3. providers.HttpProvider("http://127.0.0.1:9545")) + window.App.eventStart() » 20Decentralized Voting System Using Ethereum Blockchain 4, Login, const loginForm = document. getElementById(‘loginForm’); loginForm.addEventListener(‘submit', (event) => { event .preventDefault() 5 const voter_id const password const token document . getElementByTd('voter-id').value; document .getElementById(' password’ ).value; voter_id; const headers = { "method": "GET", ‘authorization’: “Bearer ${token} , 8 fetch(* http: //127.0.0.1:8000/login?voter_i sword}, { headers }) -then(response => { if (response.ok) { return response. json()5 } else { throw new Error(’Login failed"); } » «then(data => { if (data.role "admin') { console. log(data. role) localStorage.setItem('jwtTokenAdmin', data.token); window. location .replace(*http: //[email protected]:8080/admin.html?Authoriz ation=Bearer ${localStorage.get Item(' jwtTokenAdmin')}* ); } else if (data.role ‘user'){ localstorage. setItem('jwtTokenVoter', data.token); window. location.replace(*http: //127.0.0.1:8080/index.htm1?Authoriz ation=Bearer ${localStorage.get Item(' jwtTokenVoter')}*); } » wcatch(error => { console.error('Login failed:', error.message); Ys Ds ${voter_id}&password=${pas aDecentralized Voting System Using Ethereum Blockchain 5. Main.py # Import required modules import dotenv import os import mysql.connector from fastapi import FastAPI, HTTPException, status, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.encoders import jsonable_encoder from mysql.connector import errorcode import jwt # Loading the environment variables dotenv. load_dotenv() # Initialize the todoapi app app = FastAPI() # Define the allowed origins for CORS origins = [ /Localhost :8080", /127 [email protected]:8080", # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_method 1 allow_headers=["*"], ) # Connect to the MySQL database try: cnx = mysql.connector. connect ( user=os.environ[ 'MYSQL_USER" ], password=os.environ[ 'MYSQL_PASSWORD' ], host=os.environ[ 'MYSQL_HOST’], database=os.environ[ 'MYSQL_DB"], ) cursor = cnx.cursor() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") 2Decentralized Voting System Using Ethereum Blockchain elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exist") else: print (err) # Define the authentication middleware async def authenticate(request: Request) : try: api_key = request.headers.get('authorization').replace("Bearer so) cursor.execute("SELECT * FROM voters WHERE voter_id = %s", (api_key,)) if api_key not in [row[®] for row in cursor. fetchall()]: raise HTTPException( status_code=status.HTTP_4@1_UNAUTHORIZED, detail="Forbidden" ) except: raise HTTPException( status_code=status.HTTP_4@1_UNAUTHORIZED, detail="Forbidden” ) # Define the POST endpoint for login @app.get("/login") async def login(request: Request, voter_id: str, password: str): await authenticate(request) role = await get_role(voter_id, password) # Assuming authentication is successful, generate a token token = jwt.encode({'password': password, ‘voter_id': voter_id, ‘role’: role}, os.environ[‘SECRET_KEY'], algorithm='HS256' ) return {'token': token, ‘role’: role} # Replace ‘admin’ with the actual role based on authentication async def get_role(voter_id, password): try: cursor.execute("SELECT role FROM voters WHERE voter_id = %s AND password = %s", (voter_id, password,)) role = cursor. fetchone() if role: return role[@] else: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid voter id or password" 23Decentralized Voting System Using Ethereum Blockchain ) except mysql.connector.Error as err: print (err) raise HTTPException( status_code=status.HTTP_5@@_INTERNAL_SERVER_ERROR, detail="Database error” 6. Package,json "name": "decentralized-voting”, version": "1.0.0", ‘description" main”: ‘index. js", rf "echo \"Error: no test specified\" && exit 1” 4.6.18", 17.0.0", 4Decentralized Voting System Using Ethereum Blockchain CHAPTER 8 TESTING Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. It includes a set of techniques and methods to identify defects, bugs, performance issues and providing a reliable and quality product. The goal is to identify issues as early as possible and improve the overall quality of the system. 8.1 Types of Testing 8.1.1 Unit Testing Unit testing is a type of testing that is used to evaluate the individual units or components of a software system. This type of testing helps ensure that each unit or component of the system is working correctly and is able to perform its intended function. 8.1.2 Integration Testing Integration testing is a type of testing that is used to evaluate how well the different units or components of a software system work together. This type of testing helps to identify and resolve issues related to compatibility, performance, and data flow between the different units or components. 8.1.3 Functional Testing Functional testing is a type of testing that is used to evaluate how well a system or software performs the specific fimetions or tasks that it is designed to perform. It is done by testing the system or software with various inputs and verifying that the outputs are correct. This type of testing ensures that the system or software is working as intended and is able to perform the fimetions it was designed to perform. 25Decentralized Voting System Using Ethereum Blockchain 8.1.4 White Box Testing White box testing, also known as structural testing or glass-box testing, is a type of testing that examines the intemal structure and implementation of a software system. It involves testing the code itself and checking that itis functioning correctly and adhering to coding standards, This type of testing helps to identify and resolve issues related to logic, control flow, and data structures within the system, 8.1.4 Black Box Testing Black box testing, also known as functional testing, is a type of testing that examines the extemal behavior and interfaces of # software system. It involves testing the system from the user's perspective, without looking at the internal structure or implementation, and checking that itis functioning correctly and meeting the requirements. This type of testing helps to identify and resolve issues related to usability, compatibility, and performance. 8.2 Test Results 8.2.1 Test Case 1 ‘Test Case No. 1 ‘Test Type | Unit Test ‘Name of Test | Checking JWT Authorization Test Case Description | The objective of this test case is to check jwt authorization. Login and Password Expected Output Actual Output User should not be able to login without proper authorization. User cannot ace 88 voting or admin page without authorization, ‘Comments Working properly. 26Decentralized Voting System Using Ethereum Blockchain 8.2.2 Test Case 2 Test Case No. [2 Test Type | Functional Test ‘Name of Test | Verify user login ‘Test Case Description | The objective of this test case is to verify that user can login to the voting portal Input Voter_id and password Expected Output User must be able to login if credentials match the database, else unauthorized error is shown. ‘Actual Output | User is able to login with correct credentials only. Result Pass Comments Working properly. 8.2.3 Test Case 3 Test Case No. Test Type Unit Test Name of Test ‘Verify candidate registration Test Case Description | The objective of this test case is to verify that candidate can be registered by admin, Input | Candidate name and party. Expected Output __| Registration transaction should be successful. ‘Actual Output | Registration transaction is successful. Result Pass ‘Comments Working properly. 27Decentralized Voting System Using Ethereum Blockchain 8.2.4 Test Case 4 ‘Test Case No. 4 Test Type Unit Test ‘Name of Test Verify date registration Test Case Description The objective of this test case is to verify that date of voting ean be specified by admin. Input Starting and ending date Expected Output Date transaction should be successfil Actual Output Date transaction is successful. Result Pass ‘Comments Working properly. 8.2.5 Test Case 5 Test Case No. ‘Test Type Functional Test Name of Test Verily voting ‘Test Case Description | The objective of this test ease is to verify that voter is able to cast their vote, Input | Select a candidate and click “Vote” button. Expected Output _| Vote transaction should be successful. Actual Output ‘Vote transaction is successful. Result Pass (Comments Working properly. 28Decentralized Voting System Using Ethereum Blockchain CONCLUSION AND FUTURE ENHANCEMENT Conclusion: Decentralized Voting with Ethereum Blockchain offers a robust and transparent solution for secure elections. By leveraging blockchain technology, it ensures the integrity of votes and provides a tamper-proof platform. With continued enhancements, including improved user experience, scalability, and integration with other cutting-edge technologies, it has the potential to revolutionize the democratic process and empower citizens to participate in a trusted and efficient voting system, It represents a significant step towards building a more democratic and accountable society. Future Enhancement: In future iterations, the decentralized voting system can be enhanced by implementing additional features such as real-time vote counting, secure voter identification mechanisms, advanced data analytics for voter insights, and integration with emerging technologies like artificial intelligence and biometrics, These enhancements will further enhance the efficiency, security, and accessibility of the voting process, making it more inclusive and trustworthy. 29Decentralized Voting System Using Ethereum Bloc! SCREENSHOTS Derr rt A ta MOS BCs) err) RT Ra RU cn este) Pea) Ra erDecentralized Voting System Using Ethereum Blockchain Add Candidate ee ee ee es De Staats | 23-07-2022 1D [ midaas ) 4-07-2002 LE eee 31