private async Task testReadSpeed(string voterID, string districtContractAddress)
        {
            accessTime = 0;

            string status = "Reading";

            string keyString        = privateKey.Substring(2, 4) + privateKey.Substring(privateKey.Length - 4, 4);
            var    theContract      = web3.Eth.GetContract(getContractABI(), getContractAddress());
            var    getVotesFunction = theContract.GetFunction("VoteDetails_district");

            Bytes32TypeEncoder encoder = new Bytes32TypeEncoder();
            var byte_voter             = encoder.Encode(voterID.ToString());

            byte[] byte_key = encoder.Encode(keyString);

            System.Timers.Timer t = new System.Timers.Timer();
            t.Enabled  = true;
            t.Interval = 1;
            t.Elapsed += T_Elapsed;
            t.Start();

            var syncVotes = await getVotesFunction.CallDeserializingToObjectAsync <VoteDetailsDTO.VoteDetailsOutputDTO>(districtContractAddress, byte_voter, byte_key);

            t.Stop();

            string accessTimeInsert = "INSERT INTO `electiondb`.`accesstime` (`accessTime`, `accessName`, `accessDate`) VALUES ('" + accessTime.ToString() + "', '" + status + " votes for voter: " + voterID + "', now());";

            conn.Open();
            MySqlCommand comm = new MySqlCommand(accessTimeInsert, conn);

            comm.ExecuteNonQuery();
            conn.Close();
        }
        public async Task <bool> deployDistrictBallot()
        {
            bool success = false;

            try
            {
                MySqlCommand comm;

                //access ui elements from Task. Source of code: https://stackoverflow.com/questions/11109042/getting-the-text-in-a-richtextbox-thats-on-another-thread
                var districtID   = (string)dt_nullDistrict.Invoke(new Func <string>(() => dt_nullDistrict.Rows[selectedIndex].Cells["districtID"].Value.ToString()));
                var districtName = (string)dt_nullDistrict.Invoke(new Func <string>(() => dt_nullDistrict.Rows[selectedIndex].Cells["District Name"].Value.ToString()));

                //blockchain interactions
                string  districtKey       = "0x" + txt_districtKey.Text;
                Account sub_account       = new Account(districtKey);
                string  districtKeyString = districtKey.Substring(2, 4) + districtKey.Substring(districtKey.Length - 4, 4);
                string  keyString         = privateKey.Substring(2, 4) + privateKey.Substring(privateKey.Length - 4, 4);

                Bytes32TypeEncoder encoder                = new Bytes32TypeEncoder();
                byte[]             districtIDbyte         = encoder.Encode(districtID);
                byte[]             byte_keyString         = encoder.Encode(keyString);
                byte[]             byte_districtKeyString = encoder.Encode(districtKeyString);

                var theContract         = web3.Eth.GetContract(getContractABI(), getContractAddress());
                var spawnBallotFunction = theContract.GetFunction("spawn_ballot");
                var getChildContract    = theContract.GetFunction("getDeployedChildContracts");

                var spawnBallot = await spawnBallotFunction.SendTransactionAndWaitForReceiptAsync(account.Address, gasLimit,
                                                                                                  gasPrice, null, null, districtID, byte_districtKeyString, byte_keyString);

                var ballotAddress = await getChildContract.CallAsync <string>(byte_keyString);

                MessageBox.Show("Contract for " + districtName + " has been deployed successfully!");

                //store into the database
                //random string for the salt source:https://www.dotnetperls.com/random-string
                string salt = RandomString.GetRandomString();
                string contractAddressEncryption = "CONCAT('" + salt + "', ':', HEX(AES_ENCRYPT('" + ballotAddress + "', CONCAT('XwncLQ=dbd#qLB3p', '" + salt + "'))))";
                string contractKeyEncryption     = "CONCAT('" + salt + "', ':', HEX(AES_ENCRYPT('" + txt_districtKey.Text + "', CONCAT('XwncLQ=dbd#qLB3p', '" + salt + "'))))";

                string listContract = "UPDATE `electiondb`.`district` SET `districtContractAddress` = " + contractAddressEncryption + ", `salt` ='" + salt + "'," +
                                      "`deploymentcost` = '" + spawnBallot.GasUsed.ToString() + " wei', `districtAccountKey` = " + contractKeyEncryption + "  WHERE (`districtID` = '" + districtID + "');";
                conn.Open();
                comm = new MySqlCommand(listContract, conn);
                comm.ExecuteNonQuery();
                conn.Close();

                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error has occured: " + ex.Message, "An error has occured...", MessageBoxButtons.OK
                                , MessageBoxIcon.Error);

                success = false;
            }


            return(success);
        }
        public async Task <string> IncreaseDisapprovalsAsync(string hash, string contractAddress, string contractABI)
        {
            string result = string.Empty;

            for (int i = 0; i <= ITERATIONS_TO_RETRY; i++)
            {
                try
                {
                    var account                  = new Account(MASTER_PRIVATEKEY);
                    var web3                     = new Web3Geth(account, RPC_CLIENT);
                    var contract                 = web3.Eth.GetContract(contractABI, contractAddress);
                    var function                 = contract.GetFunction("IncreaseDisapprovals");
                    Bytes32TypeEncoder enc       = new Bytes32TypeEncoder();
                    byte[]             bhash     = hash.HexToBytes(2, hash.Length);
                    BigInteger         gasPrice  = UnitConversion.Convert.ToWei(new BigDecimal(41), UnitConversion.EthUnit.Gwei);
                    HexBigInteger      hgasPrice = new HexBigInteger(gasPrice);
                    result = await function.SendTransactionAsync(MASTER_ADDRESS, new HexBigInteger(150000), hgasPrice, new HexBigInteger(0), new object[] { bhash });

                    break;
                }
                catch (Exception ex)
                {
                    telemetryClient.TrackException(ex);
                    telemetryClient.TrackTrace($"Retry #{i}, EXCEPTION: {ex.Message}. STACKTRACE: {ex.StackTrace}");
                    Thread.Sleep(TIME_TO_SLEEP_FOR_RETRY);
                    continue;
                }
            }
            return(result);
        }
Esempio n. 4
0
        static PurchasingExtensions()
        {
            _encoder = new Bytes32TypeEncoder();
            _decoder = new StringBytes32Decoder();

            // Mapping POs
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <PurchasingProfile>();
            });

            _mapper = new Mapper(config);
        }
        public async Task <bool> deployContractTask()
        {
            string contractBytecode = txt_contractBytecode.Text;
            string contractABI      = txt_contractABI.Text;

            string             keyString = privateKey.Substring(2, 4) + privateKey.Substring(privateKey.Length - 4, 4);
            Bytes32TypeEncoder encoder   = new Bytes32TypeEncoder();

            byte[] byte_key = encoder.Encode(keyString);

            bool success = false;

            try
            {
                var contractDeployment = new ContractDeployer(txt_contractBytecode.Text)
                {
                    _key = byte_key
                };

                var deploymentHandler = web3.Eth.GetContractDeploymentHandler <ContractDeployer>();
                var deploy            = await deploymentHandler.SendRequestAndWaitForReceiptAsync(contractDeployment);

                contractAddress = deploy.ContractAddress;

                MessageBox.Show("Contract deployed successfully!", "Contract Deployed", MessageBoxButtons.OK, MessageBoxIcon.Information);

                //random string for the salt source:https://www.dotnetperls.com/random-string
                string salt = RandomString.GetRandomString();
                string contractAddressEncryption = "CONCAT('" + salt + "', ':', HEX(AES_ENCRYPT('" + contractAddress + "', CONCAT('XwncLQ=dbd#qLB3p', '" + salt + "'))))";


                //Store contract address into the database
                string listContract = "INSERT INTO `electiondb`.`smartcontracts` (`contractAddress`, `contractABI`, `contractName`, `deployedBy`,`deployDate`,`salt`,`deploymentcost`) VALUES" +
                                      " (" + contractAddressEncryption + ", '" + contractABI + "' , '" + txt_contractName.Text + "', '" + adminID + "', now(),'" + salt + "','" + deploy.GasUsed.ToString() + " wei');";
                conn.Open();
                MySqlCommand comm = new MySqlCommand(listContract, conn);
                comm.ExecuteNonQuery();
                conn.Close();

                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error has occured: " + ex.Message, "An error has occured...", MessageBoxButtons.OK
                                , MessageBoxIcon.Error);

                success = false;
            }

            return(success);
        }
Esempio n. 6
0
        public async virtual Task SetupAsync()
        {
            Byte32Encoder = new Bytes32TypeEncoder();
            await InitAutonomousTestAsync();
            await DeployIDAsync();

            string location = "somewhere";
            string hash     = "somehash";

            OwnedAttribute = await DeployAttributeAsync(location, hash, ID.GetAddress());

            NotOwnedAttribute = await DeployAttributeAsync(location, hash, "0x7e2be0405d58e50de14522b47de83383597245e8");
            await DeployAttributeOwnedCertificateAsync(location, hash);
        }
Esempio n. 7
0
        public async Task AddRentalContract(Rental rental, string password)
        {
            var abi =
                @"[ { 'constant': true, 'inputs': [ { 'name': '', 'type': 'bytes32' }, { 'name': '', 'type': 'uint256' } ], 'name': 'rentals', 'outputs': [ { 'name': 'landlord', 'type': 'address' }, { 'name': 'tenant', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [ { 'name': 'key', 'type': 'bytes32' }, { 'name': 'landlord', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'name': 'StoreRental', 'outputs': [ { 'name': 'success', 'type': 'bool' } ], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' } ]";

            var byteCode =
                "0x608060405234801561001057600080fd5b50610447806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630a8d65b614610051578063152aa7ca1461011b575b600080fd5b34801561005d57600080fd5b5061008a6004803603810190808035600019169060200190929190803590602001909291905050506101ac565b604051808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001838152602001828152602001965050505050505060405180910390f35b34801561012757600080fd5b506101926004803603810190808035600019169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001909291908035906020019092919080359060200190929190505050610244565b604051808215151515815260200191505060405180910390f35b6000602052816000526040600020818154811015156101c757fe5b9060005260206000209060060201600091509150508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060020154908060030154908060040154908060050154905086565b600061024e6103b8565b60c0604051908101604052808873ffffffffffffffffffffffffffffffffffffffff1681526020013373ffffffffffffffffffffffffffffffffffffffff1681526020018781526020018681526020018581526020018481525090506000808960001916600019168152602001908152602001600020819080600181540180825580915050906001820390600052602060002090600602016000909192909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020155606082015181600301556080820151816004015560a0820151816005015550505060019150509695505050505050565b60c060405190810160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600081526020016000815250905600a165627a7a72305820dfeb2f0f92f01e63c77c245a21f721864d33077e40ee06fcfdccb6c2c38b0e5c0029";


            //a managed account uses personal_sendTransanction with the given password, this way we don't need to unlock the account for a certain period of time
            var account = new ManagedAccount(rental.Tenant, password);

            //using the specific geth web3 library to allow us manage the mining.
            var web3    = new Nethereum.Web3.Web3("http://127.0.0.1:7545");
            var receipt = new TransactionReceipt();

            try
            {
                receipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(byteCode, rental.Tenant, new HexBigInteger(900000));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }



            var contractAddress = receipt.ContractAddress;

            var contract = web3.Eth.GetContract(abi, contractAddress);

            var storeFunction     = contract.GetFunction("StoreRental");
            var documentsFunction = contract.GetFunction("rentals");
            var t = new Bytes32TypeEncoder();

            try
            {
                var transactionHash = await storeFunction.SendTransactionAsync(from : rental.Tenant, gasPrice : null, gas : new HexBigInteger(2100000), value : null, functionInput : new object[] { "key1", rental.Landlord, rental.Tenant, rental.DepositeAmount, rental.RentalPrice, rental.Endtime, rental.ItemId });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Esempio n. 8
0
        public async Task <Attribute> DeployAsync(Attribute attribute, string owner)
        {
            Bytes32TypeEncoder encoder         = new Bytes32TypeEncoder();
            string             transactionHash = await AttributeService.DeployContractAsync(Web3, AccountService.PrivateKey, attribute.Location, encoder.Encode(attribute.Description), attribute.Hash, owner);

            TransactionReceipt receipt = await Web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(transactionHash);

            //Populating the attribute model with the new address
            attribute.Address = receipt.ContractAddress;
            attribute.Owner   = owner;

            //Iterating over certificates and deploying each one
            foreach (string key in attribute.Certificates.Keys)
            {
                Certificate cert = await _certificateFacade.DeployAsync(attribute.Certificates[key]);
                await AddCertificateAsync(attribute, cert);
            }

            return(attribute);
        }
        public async Task <bool> syncVotes(string districtAddress, string voterID)
        {
            accessTime = 0;
            System.Timers.Timer t = new System.Timers.Timer();
            t.Enabled  = true;
            t.Interval = 1;
            t.Elapsed += T_Elapsed;;
            t.Start();

            string status  = "Counted";
            bool   success = false;

            MySqlCommand     comm;
            MySqlDataAdapter adp;

            string keyString = privateKey.Substring(2, 4) + privateKey.Substring(privateKey.Length - 4, 4);

            try
            {
                var theContract      = web3.Eth.GetContract(getContractABI(), getContractAddress());
                var getVotesFunction = theContract.GetFunction("VoteDetails_district");

                Bytes32TypeEncoder encoder = new Bytes32TypeEncoder();
                var    byte_voter          = encoder.Encode(voterID.ToString());
                byte[] byte_key            = encoder.Encode(keyString);

                var syncVotes = await getVotesFunction.CallDeserializingToObjectAsync <VoteDetailsDTO.VoteDetailsOutputDTO>(districtAddress, byte_voter, byte_key);

                DataTable voteDetails = new DataTable();

                conn.Open();
                string selectVotes = "SELECT voteID, voterID, presidentVote, vicePresidentVote, senatorVote, voteString FROM electiondb.vote where voterID = " + voterID + ";";
                comm = new MySqlCommand(selectVotes, conn);
                adp  = new MySqlDataAdapter(comm);
                adp.Fill(voteDetails);
                conn.Close();

                string voteStringA = System.Text.Encoding.UTF8.GetString(syncVotes.voteStringA);
                string voteStringB = System.Text.Encoding.UTF8.GetString(syncVotes.voteStringB);
                string dateVoted   = System.Text.Encoding.UTF8.GetString(syncVotes.VoteTime);

                string voteString = voteStringA + voteStringB;

                if (!voteString.Equals(voteDetails.Rows[0][5].ToString()))
                {
                    string updateVote = "INSERT INTO `electiondb`.`votearchive` (`voteID`, `voterID`, `presidentVote`, `vicePresidentVote`, `senatorVote`, `datetimevoted`, `voteString`) " +
                                        "select `voteID`, `voterID`, `presidentVote`, `vicePresidentVote`, `senatorVote`, `datetimevoted`, `voteString` FROM `electiondb`.`vote` WHERE voteID = " + voteDetails.Rows[0][0].ToString() + ";" +
                                        "UPDATE `electiondb`.`vote` SET `voteString` = '" + voteString + "' WHERE (`voteID` = '" + voteDetails.Rows[0][0].ToString() + "');";
                    conn.Open();
                    comm = new MySqlCommand(updateVote, conn);
                    comm.ExecuteNonQuery();
                    conn.Close();

                    status = "REVERTED";
                }

                //regular expressions source: https://www.dotnetperls.com/regex-matches
                MatchCollection pres_match  = Regex.Matches(voteString, @"[1]:\d*");
                MatchCollection vpres_match = Regex.Matches(voteString, @"[2]:\d*");
                MatchCollection sen_match   = Regex.Matches(voteString, @"[3]:(\d*(,)?){12}");

                foreach (Match m in pres_match)
                {
                    foreach (Capture c in m.Captures)
                    {
                        string updateVote = "UPDATE `electiondb`.`vote` SET `presidentVote` = '" + c.Value.Substring(2) + "' WHERE (`voteID` = '" + voteDetails.Rows[0][0].ToString() + "');";
                        conn.Open();
                        comm = new MySqlCommand(updateVote, conn);
                        comm.ExecuteNonQuery();
                        conn.Close();
                    }
                }

                foreach (Match m in vpres_match)
                {
                    foreach (Capture c in m.Captures)
                    {
                        string updateVote = "UPDATE `electiondb`.`vote` SET `vicePresidentVote` = '" + c.Value.Substring(2) + "' WHERE (`voteID` = '" + voteDetails.Rows[0][0].ToString() + "');";
                        conn.Open();
                        comm = new MySqlCommand(updateVote, conn);
                        comm.ExecuteNonQuery();
                        conn.Close();
                    }
                }

                foreach (Match m in sen_match)
                {
                    foreach (Capture c in m.Captures)
                    {
                        string updateVote = "UPDATE `electiondb`.`vote` SET `senatorVote` = '" + c.Value.Substring(2) + "' WHERE (`voteID` = '" + voteDetails.Rows[0][0].ToString() + "');";
                        conn.Open();
                        comm = new MySqlCommand(updateVote, conn);
                        comm.ExecuteNonQuery();
                        conn.Close();
                    }
                }

                /*string updateDate = "UPDATE `electiondb`.`vote` SET `datetimevoted` = `datetimevoted` = STR_TO_DATE('" + dateVoted + "','%Y%m%d %h%i') WHERE (`voteID` = '"+ voteDetails.Rows[0][0].ToString() + "');";
                 * conn.Open();
                 * comm = new MySqlCommand(updateDate, conn);
                 * comm.ExecuteNonQuery();
                 * conn.Close();*/

                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occured: " + ex.Message);
                success = false;
            }

            string accessTimeInsert = "INSERT INTO `electiondb`.`accesstime` (`accessTime`, `accessName`, `accessDate`) VALUES ('" + accessTime.ToString() + "', '" + status + " votes for voter: " + voterID + "', now());";

            conn.Open();
            comm = new MySqlCommand(accessTimeInsert, conn);
            comm.ExecuteNonQuery();
            conn.Close();

            t.Stop();

            return(success);
        }
        public async Task <bool> syncVoters(string contractAddress, string voterID)
        {
            bool exists = false;

            accessTime = 0;

            System.Timers.Timer t = new System.Timers.Timer();
            t.Enabled  = true;
            t.Interval = 1;
            t.Elapsed += T_Elapsed;
            t.Start();

            string status = "Retrieved";

            MySqlCommand comm;

            try
            {
                var ballotABI        = @"[{""inputs"":[{""internalType"":""bytes32"",""name"":""_main_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_sub_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_district"",""type"":""bytes32""}],""stateMutability"":""nonpayable"",""type"":""constructor""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""Vote_Details"",""outputs"":[{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""}],""name"":""checkVoterExists"",""outputs"":[{""internalType"":""uint8"",""name"":"""",""type"":""uint8""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_precint_no"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""registerVoter"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voteStringA"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voteStringB"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_vote_date"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""vote"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""}]";
                var theContract      = web3.Eth.GetContract(ballotABI, contractAddress);
                var checkVoterExists = theContract.GetFunction("checkVoterExists");

                Bytes32TypeEncoder encoder = new Bytes32TypeEncoder();
                byte[]             theByte = encoder.Encode(voterID.ToString());

                var check = await checkVoterExists.CallDeserializingToObjectAsync <VoterDetailsDTO.VoterDetailsOutputDTO>(theByte);

                if (check.Exists.ToString() != "1")
                {
                    DataTable otherDistricts = new DataTable();

                    conn.Open();
                    string selectOtherDistricts = "SELECT districtID, CAST(AES_DECRYPT(UNHEX(SUBSTRING_INDEX(districtContractAddress, ':', - 1)), CONCAT('XwncLQ=dbd#qLB3p', SUBSTRING_INDEX(districtContractAddress, ':', 1)))AS CHAR) FROM district WHERE cast(AES_DECRYPT(UNHEX(SUBSTRING_INDEX(districtContractAddress, ':', -1)), CONCAT('XwncLQ=dbd#qLB3p', SUBSTRING_INDEX(districtContractAddress, ':', 1))) as char) != '" + contractAddress + "'";
                    comm = new MySqlCommand(selectOtherDistricts, conn);
                    MySqlDataAdapter adp = new MySqlDataAdapter(comm);
                    adp.Fill(otherDistricts);
                    conn.Close();

                    int otherDistrictCount = 0;

                    foreach (DataRow dr in otherDistricts.Rows)
                    {
                        otherDistrictCount++;

                        theContract      = web3.Eth.GetContract(ballotABI, dr.ItemArray[1].ToString());
                        checkVoterExists = theContract.GetFunction("checkVoterExists");
                        check            = await checkVoterExists.CallDeserializingToObjectAsync <VoterDetailsDTO.VoterDetailsOutputDTO>(theByte);

                        if (check.Exists.ToString() == "1")
                        {
                            status = "REVERTED";

                            string syncQuery = "INSERT INTO `electiondb`.`voterarchive` " +
                                               "(`voterID`, `firstname`, `lastname`, `middlename`, `addedBy`, `districtID`, `precinctID`, `voterStatus`, `voterPassword`, `salt`)" +
                                               "SELECT voterID, firstname, lastname, middlename, addedBy, districtID, precinctID, voterStatus, voterPassword, salt " +
                                               "FROM electiondb.voter where voterID = '" + voterID + "';" +
                                               "UPDATE `electiondb`.`voter` SET `districtID` = '" + dr.ItemArray[0].ToString() + "' WHERE (`voterID` = '" + voterID + "');";
                            conn.Open();
                            comm = new MySqlCommand(syncQuery, conn);
                            comm.ExecuteNonQuery();
                            conn.Close();

                            exists = true;
                        }

                        if (check.Exists.ToString() != "1" && otherDistrictCount == otherDistricts.Rows.Count)
                        {
                            DataTable dt = new DataTable();

                            string checkVote = "Select * from electiondb.vote where voterID = " + voterID + ";";
                            conn.Open();
                            comm = new MySqlCommand(checkVote, conn);
                            adp  = new MySqlDataAdapter(comm);
                            adp.Fill(dt);
                            conn.Close();

                            if (dt.Rows.Count > 0)
                            {
                                foreach (DataRow dtr in dt.Rows)
                                {
                                    string moveVote = "INSERT INTO `electiondb`.`votearchive` (`voteID`, `voterID`, `presidentVote`, `vicePresidentVote`, `senatorVote`, `datetimevoted`, `voteString`) " +
                                                      "select `voteID`, `voterID`, `presidentVote`, `vicePresidentVote`, `senatorVote`, `datetimevoted`, `voteString` FROM `electiondb`.`vote` " +
                                                      "WHERE voteID = " + dtr.ItemArray[0].ToString() + ";" +
                                                      "DELETE from `electiondb`.`timekeeper` where voteID = " + dtr.ItemArray[0].ToString() + ";" +
                                                      "DELETE from `electiondb`.`vote` where voteID = " + dtr.ItemArray[0].ToString() + ";";
                                    conn.Open();
                                    comm = new MySqlCommand(moveVote, conn);
                                    comm.ExecuteNonQuery();
                                    conn.Close();
                                }
                            }

                            string moveVoter = "INSERT INTO `electiondb`.`voterarchive` " +
                                               "(`voterID`, `firstname`, `lastname`, `middlename`, `addedBy`, `districtID`, `precinctID`, `voterStatus`, `voterPassword`, `salt`)" +
                                               "SELECT voterID, firstname,lastname,middlename,addedBy,districtID,precinctID,voterStatus,voterPassword,salt FROM electiondb.voter where voterID = '" + voterID + "';" +
                                               "Delete from electiondb.voter where voterID = '" + voterID + "';";

                            conn.Open();
                            comm = new MySqlCommand(moveVoter, conn);
                            comm.ExecuteNonQuery();
                            conn.Close();


                            MessageBox.Show("Voter No." + voterID + " archived");
                        }
                    }
                }
                else if (check.Exists.ToString() == "1")
                {
                    exists = true;
                }

                string precinctID    = Encoding.Default.GetString(check.precinctID);
                int    precinctIDint = int.Parse(precinctID);

                string updatePrecinct = "UPDATE `electiondb`.`voter` SET `precinctID` = " + precinctIDint.ToString() + " WHERE (`voterID` = '" + voterID + "');";
                conn.Open();
                comm = new MySqlCommand(updatePrecinct, conn);
                comm.ExecuteNonQuery();
                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string accessTimeInsert = "INSERT INTO `electiondb`.`accesstime` (`accessTime`, `accessName`, `accessDate`) VALUES ('" + accessTime.ToString() + "', '" + status + " voter information for voter: " + voterID + "', now());";

            conn.Open();
            comm = new MySqlCommand(accessTimeInsert, conn);
            comm.ExecuteNonQuery();
            conn.Close();

            t.Stop();

            return(exists);
        }
Esempio n. 11
0
 static ContractExtensions()
 {
     _encoder = new Bytes32TypeEncoder();
     _decoder = new StringBytes32Decoder();
 }
Esempio n. 12
0
        public async Task ShouldBeAbleToEncodeDecodeComplexInputOutput()
        {
            var senderAddress = "0x36BE568F38Ec9a0e5E49b775A908Dab35360167a";
            var rentalAddress = "0xb334F2Da6ed3cA1c564b151A6a260aDc15CDf596";
            var password      = "******";

            var abi =
                @"[ { 'constant': true, 'inputs': [ { 'name': '', 'type': 'bytes32' }, { 'name': '', 'type': 'uint256' } ], 'name': 'rentals', 'outputs': [ { 'name': 'landlord', 'type': 'address' }, { 'name': 'tenant', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [ { 'name': 'key', 'type': 'bytes32' }, { 'name': 'landlord', 'type': 'address' }, { 'name': 'depositeAmount', 'type': 'uint256' }, { 'name': 'rentalPrice', 'type': 'uint256' }, { 'name': 'endtime', 'type': 'uint256' }, { 'name': 'itemId', 'type': 'uint256' } ], 'name': 'StoreRental', 'outputs': [ { 'name': 'success', 'type': 'bool' } ], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' } ]";

            var byteCode =
                "0x608060405234801561001057600080fd5b50610447806100206000396000f30060806040526004361061004c576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630a8d65b614610051578063152aa7ca1461011b575b600080fd5b34801561005d57600080fd5b5061008a6004803603810190808035600019169060200190929190803590602001909291905050506101ac565b604051808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001838152602001828152602001965050505050505060405180910390f35b34801561012757600080fd5b506101926004803603810190808035600019169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001909291908035906020019092919080359060200190929190505050610244565b604051808215151515815260200191505060405180910390f35b6000602052816000526040600020818154811015156101c757fe5b9060005260206000209060060201600091509150508060000160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060010160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16908060020154908060030154908060040154908060050154905086565b600061024e6103b8565b60c0604051908101604052808873ffffffffffffffffffffffffffffffffffffffff1681526020013373ffffffffffffffffffffffffffffffffffffffff1681526020018781526020018681526020018581526020018481525090506000808960001916600019168152602001908152602001600020819080600181540180825580915050906001820390600052602060002090600602016000909192909190915060008201518160000160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060408201518160020155606082015181600301556080820151816004015560a0820151816005015550505060019150509695505050505050565b60c060405190810160405280600073ffffffffffffffffffffffffffffffffffffffff168152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160008152602001600081526020016000815250905600a165627a7a72305820dfeb2f0f92f01e63c77c245a21f721864d33077e40ee06fcfdccb6c2c38b0e5c0029";


            //a managed account uses personal_sendTransanction with the given password, this way we don't need to unlock the account for a certain period of time
            var account = new ManagedAccount(senderAddress, password);

            //using the specific geth web3 library to allow us manage the mining.
            var web3    = new Nethereum.Web3.Web3("http://127.0.0.1:7545");
            var receipt = new TransactionReceipt();

            try
            {
                receipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(byteCode, senderAddress, new HexBigInteger(900000));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }



            var contractAddress = receipt.ContractAddress;

            var contract = web3.Eth.GetContract(abi, contractAddress);

            var storeFunction     = contract.GetFunction("StoreRental");
            var documentsFunction = contract.GetFunction("rentals");
            var t = new Bytes32TypeEncoder();

            try
            {
                var transactionHash = await storeFunction.SendTransactionAsync(from : senderAddress, gasPrice : null, gas : new HexBigInteger(2100000), value : null, functionInput : new object[] { "key1", rentalAddress, 1, 1, 1, 1 });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            try
            {
                var transactionHash = await storeFunction.SendTransactionAsync(from : senderAddress, gasPrice : null, gas : new HexBigInteger(2100000), value : null, functionInput : new object[] { "key1", rentalAddress, 5, 5, 5, 5 });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var result = new Rental();

            try
            {
                result = await documentsFunction.CallDeserializingToObjectAsync <Rental>("key1", 0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var result2 = await documentsFunction.CallDeserializingToObjectAsync <Rental>("key1", 1);

            Assert.Equal("hello", result.Landlord);
            Assert.Equal("solidity is great", result.Tenant);

            Assert.Equal("hello again", result2.Landlord);
            Assert.Equal("ethereum is great", result2.Tenant);
        }
        public async Task <bool> blockchain_registerVoter()
        {
            bool         success = false;
            MySqlCommand comm;
            DataTable    voterTable = new DataTable();
            DataTable    key        = new DataTable();

            //access ui elements from Task. Source of code: https://stackoverflow.com/questions/11109042/getting-the-text-in-a-richtextbox-thats-on-another-thread
            var firstname  = (string)txt_firstname.Invoke(new Func <string>(() => txt_firstname.Text));
            var middlename = (string)txt_middlename.Invoke(new Func <string>(() => txt_middlename.Text));
            var lastname   = (string)txt_lastname.Invoke(new Func <string>(() => txt_lastname.Text));
            var district   = (int)cmb_districts.Invoke(new Func <int>(() => cmb_districts.SelectedIndex));
            var precinct   = (int)cmb_districts.Invoke(new Func <int>(() => cmb_precinct.SelectedIndex));
            var password   = (string)txt_voterPassword.Invoke(new Func <string>(() => txt_voterPassword.Text));

            setDistrictAccount(districts.Rows[district][0].ToString());

            try
            {
                //Add voters to the database
                string salt        = RandomString.GetRandomString();
                string passwordVal = "sha2(concat('" + txt_voterPassword.Text + "','" + salt + "'),512)";

                string insertVoter = "INSERT INTO `electiondb`.`voter` (`firstname`, `lastname`, `middlename`, `addedBy`, `districtID`, `precinctID`,`voterPassword`,`salt`)" +
                                     " VALUES ('" + txt_firstname.Text + "', '" + txt_lastname.Text + "', '" + txt_middlename.Text + "', '" + adminID + "', " + districts.Rows[district][0].ToString() + ", "
                                     + precincts.Rows[precinct][0].ToString() + ", " + passwordVal + ", '" + salt + "');";

                conn.Open();
                comm = new MySqlCommand(insertVoter, conn);
                comm.ExecuteNonQuery();
                conn.Close();

                conn.Open();
                string readVoter = "select voterID, districtContractAddress, middlename, precinctID from electiondb.voter c join electiondb.district d on c.districtID = d.districtID where c.firstname = '"
                                   + firstname + "' and c.lastname = '" + lastname + "' and c.middlename = '" + middlename + "' and c.districtID = " + districts.Rows[district][0].ToString() + ";";
                comm = new MySqlCommand(readVoter, conn);
                MySqlDataAdapter adp = new MySqlDataAdapter(comm);
                adp.Fill(voterTable);
                conn.Close();

                //add voters to the blockchain
                var ballotABI        = @"[{""inputs"":[{""internalType"":""bytes32"",""name"":""_main_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_sub_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_district"",""type"":""bytes32""}],""stateMutability"":""nonpayable"",""type"":""constructor""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""Vote_Details"",""outputs"":[{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""}],""name"":""checkVoterExists"",""outputs"":[{""internalType"":""uint8"",""name"":"""",""type"":""uint8""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_precint_no"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""registerVoter"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voteStringA"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voteStringB"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_vote_date"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""vote"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""}]";
                var theContract      = web3.Eth.GetContract(ballotABI, getContractAddress(districts.Rows[district][0].ToString()));
                var addVoterFunction = theContract.GetFunction("registerVoter");

                string keyString = privateKey.Substring(2, 4) + privateKey.Substring(privateKey.Length - 4, 4);

                Bytes32TypeEncoder encoder        = new Bytes32TypeEncoder();
                byte[]             voterID        = encoder.Encode(voterTable.Rows[0][0].ToString());
                byte[]             precinctID     = encoder.Encode(voterTable.Rows[0][3].ToString());
                byte[]             byte_keyString = encoder.Encode(keyString);
                var addVoter = await addVoterFunction.SendTransactionAndWaitForReceiptAsync(account.Address, gasLimit, gasPrice, null, null, voterID, precinctID, byte_keyString);

                success = true;

                MessageBox.Show("Voter successfully registered!");

                byte[] ba        = Encoding.Default.GetBytes(voterTable.Rows[0][0].ToString() + txt_middlename.Text.Substring(0, 1));
                string hexString = BitConverter.ToString(ba);
                voterCode = hexString.Replace("-", "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error has occured: " + ex.Message, "An error has occured...", MessageBoxButtons.OK
                                , MessageBoxIcon.Error);

                string deleteCandidate = "Delete from  `electiondb`.`voter` where voterID = " + voterTable.Rows[0][0].ToString() + ";";
                conn.Open();
                comm = new MySqlCommand(deleteCandidate, conn);
                comm.ExecuteNonQuery();
                conn.Close();

                success = false;
            }

            return(success);
        }
Esempio n. 14
0
 public Bytes32Type(string name) : base(name)
 {
     Decoder = new Bytes32TypeDecoder();
     Encoder = new Bytes32TypeEncoder();
 }
 static ExtensionMethods()
 {
     _encoder = new Bytes32TypeEncoder();
     _decoder = new StringBytes32Decoder();
 }
        public async Task <bool> vote()
        {
            bool success   = false;
            var  ballotABI = @"[{""inputs"":[{""internalType"":""bytes32"",""name"":""_main_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_sub_key"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_district"",""type"":""bytes32""}],""stateMutability"":""nonpayable"",""type"":""constructor""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""Vote_Details"",""outputs"":[{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""}],""name"":""checkVoterExists"",""outputs"":[{""internalType"":""uint8"",""name"":"""",""type"":""uint8""},{""internalType"":""bytes32"",""name"":"""",""type"":""bytes32""}],""stateMutability"":""view"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_precint_no"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""registerVoter"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""},{""inputs"":[{""internalType"":""bytes32"",""name"":""_voteStringA"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voteStringB"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_voter_id"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_vote_date"",""type"":""bytes32""},{""internalType"":""bytes32"",""name"":""_key"",""type"":""bytes32""}],""name"":""vote"",""outputs"":[],""stateMutability"":""nonpayable"",""type"":""function""}]";

            try
            {
                var contractAddress = getContractAddress();
                var theContract     = web3.Eth.GetContract(ballotABI, contractAddress);
                var voteFunction    = theContract.GetFunction("vote");

                string voteString = getVoteString();

                string voteStringA = "";
                string voteStringB = "";

                if (voteString.Length > 32)
                {
                    voteStringA = voteString.Substring(0, 32);
                    voteStringB = voteString.Substring(32);
                }
                else
                {
                    voteStringA = voteString;
                }

                string keyString = privateKey.Substring(0, 4) + privateKey.Substring(privateKey.Length - 4, 4);

                Bytes32TypeEncoder encoder          = new Bytes32TypeEncoder();
                byte[]             byte_voteStringA = encoder.Encode(voteStringA);
                byte[]             byte_voteStringB = encoder.Encode(voteStringB);
                byte[]             byte_voterID     = encoder.Encode(voterID);
                byte[]             byte_dateTime    = encoder.Encode(DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
                byte[]             byte_key         = encoder.Encode(keyString);

                var vote = await voteFunction.SendTransactionAndWaitForReceiptAsync(account.Address, gasLimit, gasPrice, null, null,
                                                                                    byte_voteStringA, byte_voteStringB, byte_voterID, byte_dateTime, byte_key);

                if (vote.HasErrors().Value)
                {
                    MessageBox.Show("An error on the blockchain has occurred. Voting was not successfull", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    success = false;
                }
                else
                {
                    string senatorArray = String.Join(", ", sen.ConvertAll(i => i.ToString()).ToArray());
                    string addVote      = "INSERT INTO `electiondb`.`vote` (`voterID`, `presidentVote`, `vicePresidentVote`, `senatorVote`, `datetimevoted`, `voteString`) " +
                                          "VALUES ('" + voterID + "', '" + p.ToString() + "', '" + vp.ToString() + "', '" + senatorArray + "', current_timestamp(), '" + voteString + "');";
                    conn.Open();
                    MySqlCommand comm = new MySqlCommand(addVote, conn);
                    comm.ExecuteNonQuery();
                    conn.Close();

                    success = true;
                }

                gasUsed = vote.GasUsed.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error has occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                success = false;
            }

            return(success);
        }