Beispiel #1
0
        private async void CreateContract()
        {
            InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", true);
            InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Text", "กำลังสร้างสัญญาเงินอิเล็กทรอนิกส์");
            var     contract    = Encoding.UTF8.GetBytes(contracttextbox.Text);;
            var     token       = Encoding.UTF8.GetBytes(tokentextbox.Text);;
            decimal amount      = Decimal.Parse(AmountTextBox.Text);
            ushort  noOfdecimal = Convert.ToUInt16(NoOfDecimalTextBox.Text);

            WalletContract mycontract = null;
            var            api        = new DigibyteAPI(new APIOptions {
                BaseURL = Program.InsightAPI
            });

            contractService = new ContractService(@"tsc-wallet.db", api);
            mycontract      = await contractService.CreateContract(privateKey, contract, token, amount, noOfdecimal);

            SetControlPropertyThreadSafe(progressBar1, "Value", 2);
            contractID = mycontract.ID;
            MessageBox.Show("รหัสสัญญา :" + contractID);        //test Show Contract ID

            int  CountConnect    = 0;
            bool triggerContract = false;

            transactions = new TransBlockchain();
            while (CountConnect <= 15)        //find contractID in blockchain
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Text", "กำลังตรวจสอบธุรกรรมการสร้างสัญญา");
                try
                {
                    var response = await client.GetAsync("/api/tx/" + contractID);

                    response.EnsureSuccessStatusCode();
                    var result = await response.Content.ReadAsStringAsync();

                    transactions = JsonConvert.DeserializeObject <TransBlockchain>(result);


                    if (transactions.time != 0 && transactions.blocktime != 0)
                    {
                        triggerContract = true;
                        break;
                    }

                    else
                    {
                        CountConnect++;
                        Thread.Sleep(5000);
                    }
                }
                catch
                {
                    CountConnect++;
                    Thread.Sleep(5000);
                }
            }
            SetControlPropertyThreadSafe(progressBar1, "Value", 3);
            if (!triggerContract)
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", false);
                SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                MessageBox.Show("ไม่ค้นพบสัญญาเงินอิเล็กทรอนิกส์ในบล็อกเชน :" + contractID);
                return;
            }

            resultContract = await contractService.FindContract(contractID);

            SetControlPropertyThreadSafe(progressBar1, "Value", 4);

            if (resultContract == null)      //if dont seen this transaction. exite method
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", false);
                SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                MessageBox.Show("การสร้างรหัสสัญญาไม่สำเร็จ");
                return;
            }


            //Check Block of Contract and LastBlock. because if block of contract is lastblock, calculating of cryptocurrency balance will be issue
            bool triggerAllow = false;

            CountConnect = 0;
            while (CountConnect <= 10)
            {
                try
                {
                    int ContractBlock = await api.GetBlockHeight(transactions.blockhash);

                    var LastSync = await api.GetSync();

                    int Lastblock = LastSync.blockChainHeight;
                    if (ContractBlock != Lastblock)
                    {
                        triggerAllow = true;
                        break;
                    }
                    else
                    {
                        CountConnect++;
                        Thread.Sleep(3000);
                    }
                }
                catch
                {
                    CountConnect++;
                    Thread.Sleep(3000);
                }
            }
            SetControlPropertyThreadSafe(progressBar1, "Value", 5);
            if (!triggerAllow)
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", false);
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                MessageBox.Show("ขณะนี้ยังไม่สามารถออกเงินได้ ลองอีกครั้ง");
                return;
            }

            Thread.Sleep(5000);                     //wait mined
            int issuedRepeat = 2;

start:
            InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Text", "กำลังออกเงิน");
            var walletService = contractService.CreateWalletService(resultContract, privateKey);    //Create issued Ledger
            var ledger1       = walletService.CreateLedger(OperationCode.Issue);

            await walletService.BroadcastLedger(ledger1);

            SetControlPropertyThreadSafe(progressBar1, "Value", 6);
            MessageBox.Show("รหัสการออกเงิน :" + ledger1.TxId);        //test Show issued ID

            transactions = new TransBlockchain();
            int  Count        = 0;
            bool IssueTrigger = false;

            while (Count <= 15)
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Text", "กำลังตรวจสอบธุรกรรมการออกเงิน");
                try
                {
                    var response2 = await client.GetAsync("/api/tx/" + ledger1.TxId);

                    response2.EnsureSuccessStatusCode();
                    var result = await response2.Content.ReadAsStringAsync();

                    transactions = JsonConvert.DeserializeObject <TransBlockchain>(result);


                    if (transactions.time != 0 && transactions.blocktime != 0)
                    {
                        IssueTrigger = true;
                        break;
                    }

                    else
                    {
                        Count++;
                        Thread.Sleep(5000);
                    }
                }
                catch
                {
                    Count++;
                    Thread.Sleep(5000);
                }
            }
            SetControlPropertyThreadSafe(progressBar1, "Value", 7);
            if (!IssueTrigger)     //if
            {
                InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", false);
                SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                MessageBox.Show("หมดเวลาการรอ กรุณาตรวจสอบรหัสธุรกรรมการออกเงินด้วยตัวเองที่ตัวสำรวจบล็อก :" + transactions.txid);
                return;         //exite ,method
            }

            var txContract = await api.GetTransactionInfo(contractID);

            var txIssued = await api.GetTransactionInfo(ledger1.TxId);

            if (txContract.blocktime > txIssued.blocktime)         //if Contract blocktime more than Issued blocktime. New Issued again.
            {
                if (issuedRepeat > 0)
                {
                    issuedRepeat--;
                    goto start;
                }
                else
                {
                    InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Visible", false);
                    SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                    MessageBox.Show("หมดเวลาการรอ กรุณาตรวจสอบรหัสธุรกรรมการออกเงินด้วยตัวเองที่ตัวสำรวจบล็อก :" + txIssued.txid);
                    return;
                }
            }
            InvokeHelp.SetControlPropertyThreadSafe(progressLabel, "Text", "สร้างสัญญาเงินอิเล็กทรอนิกส์สำเร็จ");
            triggerFinish = true;
            Action action = new Action(FinishCreating);

            this.BeginInvoke(action);
        }
Beispiel #2
0
        private async void ScanWallet()
        {
            timer.Stop();

            InvokeHelp.SetControlPropertyThreadSafe(refreshbutton, "Enabled", false);
            InvokeHelp.SetControlPropertyThreadSafe(rescanbutton, "Enabled", false);
            InvokeHelp.SetControlPropertyThreadSafe(sendDgbButton, "Enabled", false);
            InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Enabled", false);


            InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Visible", true);
            InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 1);
            DgbBalance = await api.GetBalance(publicKey);

            ShowDataToGrid(new List <WalletAccount>());
            if (InvokeRequired) //Invoke DGBBalancelabel
            {
                this.Invoke(new MethodInvoker(delegate { DGBBalancelabel.Text = DgbBalance.ToString(); }));
            }
            else
            {
                DGBBalancelabel.Text = DgbBalance.ToString();
            }
            string path = $"{Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}CurrentContract.txt";

            using (StreamReader sr = File.OpenText(path))
            {
                string s;
                if ((s = sr.ReadLine()) != null)
                {
                    using (var db = new LiteDatabase(connectionString))
                    {
                        var collection = db.GetCollection <MonitorContract>("Contracts");
                        CurrentContract = collection.FindOne(x => x.contract_id == s);
                    }
                    InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Text", "แก้ไข");
                }
                else
                {
                    InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Text", "เพิ่ม");

                    ShowDataToGrid(new List <WalletAccount>());
                    InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Visible", false);
                    InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Enabled", true);    //try
                    return;
                }
            }

            if (CurrentContract == null)
            {
                InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Enabled", true);        //try
                return;
            }

            List <String> pbkey = new List <string>();

            try
            {
                int i         = 0;
                int totalPage = 1;

                bool stopLimit = false;
                LastBlockHeight = 0;
                string ownerpubkey = CurrentContract.owner_pubkey;
                while (i < totalPage && !stopLimit)
                {
                    var response = await client.GetAsync($"/api/txs/?address={ownerpubkey}&pageNum={i}");

                    response.EnsureSuccessStatusCode();
                    var result = await response.Content.ReadAsStringAsync();

                    transactions = JsonConvert.DeserializeObject <APITransByAddr>(result);
                    totalPage    = transactions.pagesTotal;
                    List <Tx> Address = transactions.txs;

                    foreach (var datatx in Address)
                    {
                        var height = await api.GetBlockHeight(datatx.blockhash);

                        if (height > CurrentContract.blockheight)       //only BlockHeight more than BlockHeight in DB Contract
                        {
                            if (LastBlockHeight == 0)
                            {
                                LastBlockHeight = height;
                            }

                            foreach (var vins in datatx.vin)
                            {
                                pbkey.Add(vins.addr);
                            }
                            foreach (var vout in datatx.vout)
                            {
                                if (vout.scriptPubKey.addresses != null)
                                {
                                    foreach (var addr in vout.scriptPubKey.addresses)
                                    {
                                        pbkey.Add(addr.ToString());
                                    }
                                }
                            }
                        }
                        else
                        {
                            stopLimit = true;
                            break;
                        }
                    }
                    i++;
                }
                pbkey = pbkey.Distinct().ToList();              //Distince wallet
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 2);

                List <string> walletInDb   = new List <string>();
                List <string> contractInDb = new List <string>();
                using (var db = new LiteDatabase(connectionString))                     //Compare present wallet in api  with wallet in db. Insert difference wallet(new wallet) to db
                {
                    var collection  = db.GetCollection <WalletAccount>("Accounts");
                    var walletInDb1 = collection.Find(x => x.account_id.contract_id == CurrentContract.contract_id).ToList();

                    if (walletInDb1.Count() != 0)
                    {
                        walletInDb = walletInDb1.Select(x => x.account_id.publickey).ToList();
                        pbkey      = pbkey.Except(walletInDb).ToList();
                    }
                }
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 3);
                var a1 = pbkey.IndexOf(CurrentContract.owner_pubkey);          //remove owner public key
                if (a1 >= 0)
                {
                    pbkey.RemoveAt(a1);
                }
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 4);

                if (pbkey.Count() != 0)                                 //if it have got new wallet. Insert it.
                {
                    using (var db = new LiteDatabase(connectionString)) //Insert Wallet
                    {
                        var collection = db.GetCollection <WalletAccount>("Accounts");
                        foreach (var tx in pbkey)
                        {
                            var account = new WalletAccount
                            {
                                account_id = new KeyAccount
                                {
                                    contract_id = CurrentContract.contract_id,
                                    publickey   = tx.ToString()
                                }
                            };
                            collection.Insert(account);
                        }
                    }
                    using (var db = new LiteDatabase(connectionString))                     //Compare present wallet in api  with wallet in db. Insert difference wallet(new wallet) to db
                    {
                        var collection = db.GetCollection <MonitorContract>("Contracts");
                        CurrentContract.blockheight = LastBlockHeight;
                        collection.Update(CurrentContract);
                    }
                }
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 5);
                using (var db = new LiteDatabase(connectionString))
                {
                    var collection  = db.GetCollection <WalletAccount>("Accounts");
                    var walletInDb1 = collection.Find(x => x.account_id.contract_id == CurrentContract.contract_id);
                    if (walletInDb1.Count() != 0)
                    {
                        walletInDb = walletInDb1.Select(x => x.account_id.publickey).ToList();

                        foreach (var wallet in walletInDb)
                        {
                            var balance = await api.GetBalance(wallet);

                            var lessMoney = collection.FindOne(x => x.account_id.contract_id == CurrentContract.contract_id && x.account_id.publickey == wallet);
                            lessMoney.balance = balance;
                            collection.Update(lessMoney);
                        }
                    }
                    WalletInDb = collection.Find(x => x.account_id.contract_id == CurrentContract.contract_id).ToList();
                }
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 6);
            }

            catch (Exception e)
            {
                MessageBox.Show("การเชื่อมต่อตัวสำรวจบล็อกมีปัญหา โปรดลองใหม่ภายหลัง");
                //MessageBox.Show(e.Message);
                using (var db = new LiteDatabase(connectionString))     //if cannot use transaction in blockchian. Use last data in databasse
                {
                    var collection = db.GetCollection <WalletAccount>("Accounts");
                    WalletInDb = collection.Find(x => x.account_id.contract_id == CurrentContract.contract_id).ToList();
                }
            }
            if (WalletInDb != null)
            {
                ShowDataToGrid(WalletInDb);
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Value", 7);
                InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Visible", false);
            }
            InvokeHelp.SetControlPropertyThreadSafe(progressBar1, "Visible", false);

            InvokeHelp.SetControlPropertyThreadSafe(refreshbutton, "Enabled", true);
            InvokeHelp.SetControlPropertyThreadSafe(rescanbutton, "Enabled", true);
            InvokeHelp.SetControlPropertyThreadSafe(sendDgbButton, "Enabled", true);
            InvokeHelp.SetControlPropertyThreadSafe(addcontractbutton, "Enabled", true);

            LowMoneyWallet = WalletInDb.FindAll(x => x.balance < Properties.Settings.Default.minBalance);  //Find Wallet is low money
            IsDone         = true;
            timer.Start();
            AutoSendDGB();
        }