def traceById(): productID = request.args.get("productID") result = [] if not isinstance(productID, str): return make_response("argument productID should be str!", 404) productList = [productID] ethereum = Ethereum() ethereum.get_contract_instance( "0x8d592ad6DA67C3FdDe95a3cD8c33441F29C39836") while len(productList) > 0: curID = productList.pop() ipfsAddress = ethereum.getHash(curID) if ipfsAddress == "false": print("curID " + curID + " is missing") result.append({"productID": curID}) continue print(ipfsAddress) Itemdata = db.ipfs.Content.get(ipfsAddress) for materialID in Itemdata["materialsID"]: productList.insert(0, materialID) result.append(Itemdata) print(result) if len(result) == 1 and result[0].keys() == 1: response = make_response("The productID " + productID + "is not found", 404) else: response = make_response(jsonify(result), 200) return response
def blockchain_add(record_list): ballot_interface = self.ethereum.getBallotInterface() ballot_address = record_list[0]['ballot_address'] ethererum = Ethereum() d = ethererum.interact_give_right_to_vote(ballot_address, voter_addres, ballot_interface) return d
class Vote(LoginRequiredMixin, View): def __init__(self): super().__init__() self.ethereum = Ethereum() def post(self, request, _ballot_id): try: ballot_id = int(_ballot_id) print(ballot_id) (voter_address, voter_private_key, voter_public_key) = request_address_register_check_local( request.user, ballot_id ) voted_index = int(request.POST['voted_index']) ballot_address = (request.POST['ballot_address']) voter_password = (request.POST['voter_password']) except: raise Http404("Error setting initial values.") tx_hash = self.ethereum.vote(ballot_address, voted_index, voter_address, voter_password) request.session['vote_transaction'] = tx_hash return HttpResponseRedirect("/vote/" + str(ballot_id)) def get(self, request, _ballot_id): try: username = int(request.user.username) ballot_id = int(_ballot_id) vote_transaction = request.session.get('vote_transaction', None) (voter_address, voter_private_key, voter_public_key) = request_address_register_check_local( request.user, ballot_id ) if vote_transaction is not None: del request.session['vote_transaction'] request.session.modified = True except: return Http404("Error setting initial values.") # Get the list of ballots the user is eligable in available_ballots_list = NetworkRequest.searchUserAvailableBallots(username).wait(5) ballot_info = available_ballots_list[next(index for (index, d) in enumerate(available_ballots_list) if d["ballot_id"] == ballot_id)] ballot_address = ballot_info['ballot_address'] return render(request, 'vote.html', { 'ballot_info' : self.ethereum.ballotInfo(ballot_address), 'user_info' : self.ethereum.userInfo(ballot_address, voter_address), 'ballot_id' : ballot_id, 'ballot_address' : ballot_address, 'vote_transaction' : vote_transaction })
def addById(): newData: dict = json.loads(request.get_data()) content: db.ipfs.Content = None try: content = db.ipfs.Content(newData) except Exception: print(traceback.print_exc()) return make_response("format Error", 404) ipfsAddr = content.addtoIPFS() if not isinstance(ipfsAddr, str): return make_response("Error when add to IPFS", 404) print("ipfsAddr has been added: ", ipfsAddr) ethereum = Ethereum() ethereum.get_contract_instance( "0x8d592ad6DA67C3FdDe95a3cD8c33441F29C39836") ethereum.newHash(ipfsAddr) ethereum.newRelation(content.productID, ipfsAddr) print(ethereum.getHash(content.productID) == ipfsAddr) # print(productID) # print(ethereum.getHash(productID)) # # 建立新关 return make_response("upload success", 200)
def main(): # print the connection string we will use to connect print("[initialSetup] Connecting to database\n" " -> database:'%s' user:'******' host:'%s'" % (postgres_database, postgres_user, postgres_host)) # get a connection, if a connect cannot be made an exception will be raised here connection = psycopg2.connect(database=postgres_database, user=postgres_user, host=postgres_host, password=postgres_password) cursor = connection.cursor() print("[initialSetup] Creating tables if they do not exist.") # Table to hold token request information cursor.execute("CREATE TABLE IF NOT EXISTS available_ballots (" "ballot_id serial UNIQUE PRIMARY KEY, " "ballot_name varchar(500) UNIQUE NOT NULL, " "ballot_address varchar(500) UNIQUE NOT NULL, " "created_on timestamp DEFAULT CURRENT_TIMESTAMP, " "ballot_interface varchar(6000) NOT NULL, " "ballot_end_date integer NOT NULL" ");") cursor.execute( "CREATE TABLE IF NOT EXISTS ballot_register (" "ballot_register_id serial UNIQUE PRIMARY KEY, " "user_id integer NOT NULL, " "ballot_id integer NOT NULL REFERENCES available_ballots(ballot_id) ON DELETE CASCADE, " "created_on timestamp DEFAULT CURRENT_TIMESTAMP, " "UNIQUE (user_id, ballot_id)" ");") connection.commit() #TODO remove test data try: e = Ethereum() ballot_interface = '' #str(e.getBallotInterface()) cursor.execute( "INSERT INTO available_ballots (ballot_id, ballot_name, ballot_address, ballot_interface, ballot_end_date) VALUES (%s, %s, %s, %s, %s);", (1234, 'Election of the Member of Parliament for the Harborne Constituency', '0x80cc71dbd709104d54afdd0a09413571c1f1f2c9', pickle.dumps(ballot_interface), 1603238400)) cursor.execute( "INSERT INTO available_ballots (ballot_id, ballot_name, ballot_address, ballot_interface, ballot_end_date) VALUES (%s, %s, %s, %s, %s);", (4321, 'Election of Police and Crime Commissioner for Edgbaston area', '0x7439C3A100eD66a411b2b1ff9772aB9E9B9060A2', ballot_interface, 1603238400)) # cursor.execute("INSERT INTO available_ballots (ballot_id, ballot_name, ballot_address, ballot_interface, ballot_end_date) VALUES (%s, %s, %s, %s, %s);", # (5432, 'Birmigham City Council', '0xB476f990B00995ae3F70C9A972811E6fF506De66', ballot_interface, 1603238400)) cursor.execute( "INSERT INTO available_ballots (ballot_id, ballot_name, ballot_address, ballot_interface, ballot_end_date) VALUES (%s, %s, %s, %s, %s);", (6543, 'Referendum on the United Kingdoms membership of the European Union', '0x9c932c2e3866a06b89f0ed2496ddd4240e718a5a', pickle.dumps(ballot_interface), 1603238400)) # connection.commit() except Exception as e: print("[initialSetup] Error inserting test data in available_ballots.") # print("\n\n\n", e, "\n\n\n") try: cursor.execute( "INSERT INTO ballot_register (user_id, ballot_id) VALUES (1234, 1234);" ) cursor.execute( "INSERT INTO ballot_register (user_id, ballot_id) VALUES (1234, 6543);" ) cursor.execute( "INSERT INTO ballot_register (user_id, ballot_id) VALUES (2345, 6543);" ) connection.commit() except Exception as e: print("[initialSetup] Error inserting test data in ballot_register.") # print(e) cursor.close() connection.close()
def __init__(self): super().__init__() self.ethereum = Ethereum()
class RequestHandler(amp.AMP): def __init__(self): super().__init__() self.ethereum = Ethereum() @OnlineBallotRegulator_RequestContractABI.responder def request_contract_abi(self): def request(param): interface = self.ethereum.getBallotInterface() dumps = pickle.dumps(interface) return {'ok': (dumps)} def request_errback(failure): raise failure.raiseException() d = defer.Deferred() d.addCallback(request).addErrback(request_errback) d.callback(True) return d @OnlineBallotRegulator_RegisterUserIdForBallotId.responder def insert_into_ballot_register_user_id_ballot_id(self, user_id, ballot_id): print( '[RequestHandler - insert_into_ballot_register_user_id_ballot_id] Received request : user_id:%d, ballot_id:%d' % (user_id, ballot_id)) databasequery = self.factory.get_databasequery() deferred = databasequery.insert_into_ballot_register_user_id_ballot_id( user_id, ballot_id) return deferred @OnlineBallotRegulator_SearchBallotRegisterForUserId.responder def search_ballot_register_for_user_id(self, user_id): print( '[RequestHandler - request_retrieve_ballots] Received request : user_id:%d ' % (user_id)) databasequery = self.factory.get_databasequery() deferred = databasequery.search_ballot_register_for_user_id(user_id) return deferred @OnlineBallotRegulator_RegisterBallotId.responder def register_ballot(self, ballot_name, ballot_options_array_pickled, ballot_end_date): ballot_options_array = pickle.loads(ballot_options_array_pickled) print( '[RequestHandler - register_ballot] Received request : name:%s \n' ' With options: %s' % (ballot_name, ballot_options_array)) ballot_interface = 'empty' #pickle.dumps(self.ethereum.getBallotInterface()) ballot_address = self.ethereum.registerBallot(ballot_name, ballot_end_date, ballot_options_array) databasequery = self.factory.get_databasequery() deferred = databasequery.insert_into_ballots_available( ballot_name, ballot_address, ballot_interface, ballot_end_date) return deferred @OnlineBallotRegulator_SearchBallotsAvailableForAllBallots.responder def search_ballots_available_for_all_ballots(self): print( '[RequestHandler - search_ballots_available_for_all_ballots] Received request for all ballots' ) databasequery = self.factory.get_databasequery() deferred = databasequery.search_ballots_available_for_all_ballots() return deferred @OnlineBallotRegulator_RegisterVoterAddressBallotId.responder def register_voter_address_ballot_id(self, voter_addres, ballot_id): databasequery = self.factory.get_databasequery() defered = databasequery.search_ballots_available_for_ballot_id( ballot_id) def search_ballot_id_errback(failure): raise failure.raiseException() def search_ballot_id_format_results(pickled_result): # First unpickle the results. result = pickle.loads(pickled_result['ok']) # Transform the list results into a dictionary. record_list = [] for record in result: mapper = {} mapper['ballot_id'] = record[0] mapper['ballot_name'] = record[1] mapper['ballot_address'] = record[2] mapper['timestamp'] = record[3] mapper['ballot_interface'] = record[4] mapper['ballot_end_date'] = record[5] # Append each row's dictionary to a list record_list.append(mapper) return record_list results = defered.addCallback(search_ballot_id_format_results ).addErrback(search_ballot_id_errback) def blockchain_add(record_list): ballot_interface = self.ethereum.getBallotInterface() ballot_address = record_list[0]['ballot_address'] ethererum = Ethereum() d = ethererum.interact_give_right_to_vote(ballot_address, voter_addres, ballot_interface) return d def blockchain_add_errback(failure): raise failure.raiseException() blockchain_add_defered = results.addCallback( blockchain_add).addErrback(blockchain_add_errback) def return_res(result): response = str(result) return {'ok': response} def return_res_errback(failuire): print("return_res_errback\n\n", failuire.getErrorMessage()) raise failuire.raiseException() return_defered = blockchain_add_defered.addCallback( return_res).addErrback(return_res_errback) return return_defered
class RegisterForBallot(LoginRequiredMixin, View): def __init__(self): super().__init__() self.ethereum = Ethereum() def post(self, request, param_ballot_id): try: ballot_id = int(param_ballot_id) username = int(request.user.username) password = request.POST['register_password'] except ValueError: raise Http404("Couldn't cast ballot_id or username to int") (token, signed_token) = self.request_token_sign(ballot_id, request.user, username) (voter_address, voter_private_key, voter_public_key) = self.request_address_register(request.user, ballot_id, token, signed_token, password) request.session['register_ballot_' + str(ballot_id)] = datetime.datetime.now().strftime('%s') # Save our request time to the session. return HttpResponseRedirect('/register_for_ballot/' + str(ballot_id)) def get(self, request, param_ballot_id): try: ballot_id = int(param_ballot_id) username = int(request.user.username) except ValueError: raise Http404("Couldn't cast ballot_id or username to int") (token, signed_token) = request_token_sign_check_local(ballot_id, request.user) (voter_address, voter_private_key, voter_public_key) = request_address_register_check_local(request.user, ballot_id) html = "<h1>DEMO PURPOSE ONLY - remove this in prod</h1>" \ "<div>Token:" \ "<p style='word-wrap: break-word'>%s</p>" \ "Signed token:" \ "<p style='word-wrap: break-word'>%s</p>" \ "voter_address:" \ "<p style='word-wrap: break-word'>%s</p>" \ "voter_private_key:" \ "<p style='word-wrap: break-word'>%s</p>" \ "voter_public_key:" \ "<p style='word-wrap: break-word'>%s</p></div>" \ "" % (token, signed_token, voter_address, voter_private_key, voter_public_key) return HttpResponse(html) def generateEthereumAddress(self): # Generate address keccak = sha3.keccak_256() priv = SigningKey.generate(curve=SECP256k1) pub = priv.get_verifying_key().to_string() keccak.update(pub) hex_address = keccak.hexdigest()[24:] private_key = priv.to_string().hex() public_key = pub.hex() address = "0x" + hex_address return (private_key, public_key, address) def request_address_register(self, user_object, ballot_id, token, signed_token, password): local_address_register = request_address_register_check_local(user_object, ballot_id) if not None in local_address_register: return local_address_register (private_key, public_key, address) = self.generateEthereumAddress() assert address == self.ethereum.registerPrivateKey(private_key, password) # Throws if there's a problem NetworkRequest.requestRegisterBallotidVoteraddress(ballot_id, signed_token, token, address)#.wait(5) # Save our address & keys request_register_address = RegisterAddress( user=user_object, ballot_id=ballot_id, voter_address=address, voter_private_key=private_key, voter_public_key=public_key ) request_register_address.save() return (address, private_key, public_key ) def request_token_sign(self, ballot_id, user_object, username): local_token_sign = request_token_sign_check_local(ballot_id, user_object) if not None in local_token_sign: return local_token_sign # Get public key ascociated with this ballot ballot_publicKey = NetworkRequest.getBallotPublicKey(ballot_id).wait(5) # Create our RSA key object public_key = RSA.importKey(ballot_publicKey) # Generate our token token = str(random.getrandbits(128)).encode() # Blind our token random_number = SystemRandom().randrange(public_key.n >> 10, public_key.n) blinded_token = public_key.blind(token, random_number) # Request the OnlineAccountVerifier to sign this token signed_blind_token = NetworkRequest.requestSignOfToken(username, ballot_id, blinded_token).wait(5) # Unblind the token & check the signiture signed_token = public_key.unblind(signed_blind_token, random_number) sig_check = public_key.verify(token, (signed_token, "")) if not sig_check: raise NetworkExceptions.BadSignitureFromSignedToken(signed_token, token, ballot_id) # Save our request progress. request_signiture_model = RequestSigniture( user=user_object, ballot_id=ballot_id, token=str(token.decode()), token_signed=str(signed_token) ) request_signiture_model.save() return (token, signed_token)