Beispiel #1
0
        public TransactionBuilder AddOutput(long value, Script script)
        {
            var transactionOutput = new TransactionOut(value, script);

            Transaction.TransactionOut.Add(transactionOutput);
            return(this);
        }
        public TransactionOut GetTransactionIn(BcBaseTransaction transaction, IEnumerable <BlockChainAddress> bcAddrs, Networks network)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            if (bcAddrs == null)
            {
                throw new ArgumentNullException(nameof(bcAddrs));
            }

            var publicKeyHashes = bcAddrs.Select(bcAddr => bcAddr.PublicKeyHash);
            var blockChain      = _blockChainStore.GetBlockChain();
            var memPool         = MemoryPool.Instance();

            foreach (var txIn in transaction.TransactionIn)
            {
                var nCbtxIn = txIn as TransactionInNoneCoinbase;
                if (nCbtxIn == null || nCbtxIn.Outpoint == null)
                {
                    continue;
                }

                var               previousTx          = blockChain.GetTransaction(nCbtxIn.Outpoint.Hash);
                TransactionOut    previousTxOut       = null;
                BcBaseTransaction monetaryTransaction = null;
                if (previousTx == null || (monetaryTransaction = (previousTx as BcBaseTransaction)) == null || monetaryTransaction.TransactionOut == null)
                {
                    previousTxOut = memPool.GetUnspentTransaction(nCbtxIn.Outpoint.Hash, nCbtxIn.Outpoint.Index);
                    if (previousTxOut == null || (monetaryTransaction = (previousTx as BcBaseTransaction)) == null)
                    {
                        continue;
                    }
                }
                else
                {
                    previousTxOut = monetaryTransaction.TransactionOut.ElementAtOrDefault((int)nCbtxIn.Outpoint.Index);
                }

                if (previousTxOut == null || previousTxOut.Script == null || publicKeyHashes.All(publicKeyHash => !previousTxOut.Script.ContainsPublicKeyHash(publicKeyHash)))
                {
                    continue;
                }

                return(previousTxOut);
            }

            return(null);
        }
        public long CalculateBalance(BcBaseTransaction transaction, IEnumerable <BlockChainAddress> bcAddrs, Networks network)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            if (bcAddrs == null)
            {
                throw new ArgumentNullException(nameof(bcAddrs));
            }

            var            txIn            = GetTransactionIn(transaction, bcAddrs, network) as TransactionOut;
            var            publicKeyHashes = bcAddrs.Select(bcAddr => bcAddr.PublicKeyHash);
            TransactionOut txOut           = null;

            foreach (var transactionOut in transaction.TransactionOut)
            {
                var script = transactionOut.Script;
                if (publicKeyHashes.Any(publicKeyHash => script.ContainsPublicKeyHash(publicKeyHash)))
                {
                    txOut = transactionOut as TransactionOut;
                }
            }

            var noneCoinBaseTransaction = transaction as NoneCoinbaseTransaction;

            if (noneCoinBaseTransaction != null)
            {
                if (txOut == null)
                {
                    return(0);
                }

                return(-(txIn.Value - txOut.Value));
            }

            if (txOut == null)
            {
                return(0);
            }

            return(txOut.Value);
        }
        public async Task <ActionResult <TransactionOut> > GetTransaction(int id)
        {
            try
            {
                var transactionDto = _context.Transactions
                                     .AsNoTracking()
                                     .FirstOrDefault(t => t.ID == id);

                if (transactionDto == null)
                {
                    return(NotFound());
                }

                string[]          productIDs      = transactionDto.ProductIDs.Split(',');
                string[]          productQuantity = transactionDto.ProductQuantity.Split(',');
                List <ProductOut> prodList        = new List <ProductOut>();
                int i = 0;
                foreach (var productId in productIDs)
                {
                    if (!string.IsNullOrEmpty(productId))
                    {
                        var product = await _productsController.GetProduct(Convert.ToInt32(productId.Trim()));

                        if (product == null)
                        {
                            continue;
                        }
                        product.Value.Quantity = Convert.ToInt32(productQuantity[i].Trim());
                        prodList.Add(product.Value);
                        i++;
                    }
                }
                var transactionOut = new TransactionOut(_context, transactionDto);
                transactionOut.ProductDetails = prodList;

                return(transactionOut);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }
        public TransactionOut GetTransactionIn(BcBaseTransaction transaction, Networks network)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            var blockChain = _blockChainStore.GetBlockChain();

            foreach (var txIn in transaction.TransactionIn)
            {
                var nCbtxIn = txIn as TransactionInNoneCoinbase;
                if (nCbtxIn == null || nCbtxIn.Outpoint == null)
                {
                    continue;
                }

                var               previousTx          = blockChain.GetTransaction(nCbtxIn.Outpoint.Hash);
                TransactionOut    previousTxOut       = null;
                BcBaseTransaction monetaryTransaction = null;
                if (previousTx == null || (monetaryTransaction = (previousTx as BcBaseTransaction)) == null || monetaryTransaction.TransactionOut == null)
                {
                    previousTxOut = MemoryPool.Instance().GetUnspentTransaction(nCbtxIn.Outpoint.Hash, nCbtxIn.Outpoint.Index);
                    if (previousTxOut == null || (monetaryTransaction = (previousTx as BcBaseTransaction)) == null)
                    {
                        continue;
                    }
                }
                else
                {
                    previousTxOut = monetaryTransaction.TransactionOut.ElementAtOrDefault((int)nCbtxIn.Outpoint.Index);
                    if (previousTxOut == null || previousTxOut.Script == null)
                    {
                        continue;
                    }
                }


                return(previousTxOut);
            }

            return(null);
        }
    public bool verifyTransaction(string verifyWalletAddr, long verifyAmount)
    {
        if (debugLevel > 0)
        {
            Debug.Log("BlockchainDataManager: verifyTransaction: " + verifyWalletAddr + " amount: " + verifyAmount);
        }

        if (this.mTransaction == null)
        {
            Debug.LogError("BlockchainDataManager: verifyTransaction: no transaction available!");
            return(false);
        }

        long totalSatoshis = 0;

        for (int i = 0; i < mTransaction.outTransactions.Count; i++)
        {
            TransactionOut tOut = mTransaction.outTransactions[i];
            if (tOut.addr.CompareTo(verifyWalletAddr) == 0)
            {
                if (debugLevel > 0)
                {
                    Debug.Log("BlockchainDataManager: verifyTransaction: address match: amount: " + tOut.value);
                }
                totalSatoshis += (long)tOut.value;
            }
        }

        if (debugLevel > 0)
        {
            Debug.Log("BlockchainDataManager: verifyTransaction: amountToVerify: " + verifyAmount + " verified: " + totalSatoshis);
        }

        if (totalSatoshis >= verifyAmount)
        {
            return(true);
        }
        else
        {
            return(false);
        }
    }
Beispiel #7
0
        public override void SyncUpdate()
        {
            lock (AsyncElectrumScheduleService.Transactions)
            {
                AsyncElectrumScheduleService.SetStatus("Сверка транзакций из Electrum [" + AsyncElectrumScheduleService.Transactions.Count + " элементов] с базой данных");
                bool exist_new_tx = false;
                foreach (TransactionWalletHistoryResponseClass TransactionWallet in AsyncElectrumScheduleService.Transactions.Where(x => x.confirmations > MinRequedCountConfirmations))
                {
                    if (string.IsNullOrWhiteSpace(TransactionWallet.txid))
                    {
                        AsyncElectrumScheduleService.SetStatus("Прочитана транзакция из Electrum JSONRPC с пустым txid: " + TransactionWallet.ToString(), AbstractAsyncScheduler.StatusTypes.ErrorStatus);
                        AsyncElectrumScheduleService.SetStatus("Транзакция с пустым txid будет пропущена");
                        continue;
                    }

                    BtcTransactionModel btcTransaction;
                    try
                    {
                        btcTransaction = db.Set <BtcTransactionModel>().SingleOrDefault(x => x.TxId == TransactionWallet.txid);
                    }
                    catch (Exception e)
                    {
                        AsyncElectrumScheduleService.SetStatus("Ошибка поиска транзакции в БД SingleOrDefault(x => x.TxId == '" + TransactionWallet.txid + "')" + e.Message, AbstractAsyncScheduler.StatusTypes.ErrorStatus);
                        AsyncElectrumScheduleService.SetStatus("Ошибочная транзакция будет пропущена");
                        continue;
                    }

                    if (btcTransaction is null)
                    {
                        exist_new_tx = true;
                        AsyncElectrumScheduleService.SetStatus("Новая транзакция для записи в БД: " + TransactionWallet.ToString());
                        btcTransaction = new BtcTransactionModel()
                        {
                            TxId = TransactionWallet.txid,
                            Sum  = glob_tools.GetDoubleFromString(TransactionWallet.value)
                        };

                        db.Add(btcTransaction);
                        db.SaveChanges();

                        foreach (TransactionWalletHistoryResponseOutputsClass TransactionOut in TransactionWallet.outputs.Where(x => AsyncElectrumScheduleService.ElectrumClient?.IsAddressMine(x.address)?.result == true))
                        {
                            AsyncElectrumScheduleService.SetStatus("Запись нового TxOut: " + TransactionOut.ToString());
                            BtcTransactionOutModel btcTransactionOut = new BtcTransactionOutModel()
                            {
                                BtcTransactionModelId = btcTransaction.Id,
                                Sum         = glob_tools.GetDoubleFromString(TransactionOut.value),
                                Information = "txid:" + TransactionWallet.txid,
                                Address     = TransactionOut.address,
                                IsMine      = AsyncElectrumScheduleService.ElectrumClient.IsAddressMine(TransactionOut.address)?.result ?? false
                            };
                            db.Add(btcTransactionOut);
                            db.SaveChanges();

                            AsyncElectrumScheduleService.SetStatus("Поиск пользователя по BTC адресу > db.Users.SingleOrDefault(x => x.BitcoinAddress == '" + TransactionOut.address + "')");
                            UserModel user = db.Set <UserModel>().SingleOrDefault(x => x.BitcoinAddress == TransactionOut.address);
                            if (!(user is null))
                            {
                                AsyncElectrumScheduleService.SetStatus("Пользователь найден: " + user.ToString());
                                btcTransactionOut.UserId = user.Id;
                                db.Update(btcTransactionOut);
                                //
                                ///int fiat_sum = (int)(btcTransactionOut.Sum * options.Value.CurrentBtcRate);
                                user.BalanceBTC += btcTransactionOut.Sum;
                                db.Update(user);

                                string notify = "Пополнение /balance +" + string.Format("{0:F8}", Math.Round(btcTransactionOut.Sum, 8)) + "=" + user.BalanceBTC + " BTC";

                                db.Add(new eCommerceJournalModel()
                                {
                                    BaseObjectId   = btcTransactionOut.Id,
                                    TypeBaseObject = TypesBaseObject.TxOut,
                                    ClientId       = user.Id,
                                    SumBTC         = btcTransactionOut.Sum,
                                    Information    = notify
                                });
                                db.Add(new MessageModel()
                                {
                                    Information = notify, SenderId = null, RecipientId = user.Id, NeedTelegramNotify = user.TelegramId != default
                                });
        public string printToString()
        {
            string tempLog = "";

            tempLog += "\t";
            tempLog += " ver: " + this.ver;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " weight: " + this.weight;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " block_height: " + this.block_height;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " relayed_by: " + this.relayed_by;
            tempLog += "\n";

            // out
            for (int i = 0; i < outTransactions.Count; i++)
            {
                TransactionOut outT = outTransactions[i];

                tempLog += "\t";
                tempLog += " out[" + i + "]";
                tempLog += "\n";

                tempLog += outT.printToString();
            }

            tempLog += "\t";
            tempLog += " lock_time: " + this.lock_time;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " size: " + this.size;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " rbf: " + this.rbf;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " double_spend: " + this.double_spend;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " time: " + this.time;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " tx_index: " + this.tx_index;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " vin_sz: " + this.vin_sz;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " hash: " + this.hash;
            tempLog += "\n";

            tempLog += "\t";
            tempLog += " vout_sz: " + this.vout_sz;
            tempLog += "\n";

            return(tempLog);
        }
        public int vout_sz       = 0;  // 2

        //public void parseFromDict(Dictionary<string, object> transactionDict)
        public void parseFromDict(JSONNode transactionDict)
        {
            if (transactionDict["ver"] != null)
            {
                //this.ver = int.Parse((string)transactionDict["ver"]);
                this.ver = transactionDict["ver"].AsInt;
            }

            if (transactionDict["weight"] != null)
            {
                this.weight = transactionDict["weight"].AsInt;
            }

            // only for verified transactions
            if (transactionDict["block_height"] != null)
            {
                this.block_height = transactionDict["block_height"].AsDouble;
            }

            if (transactionDict["relayed_by"] != null)
            {
                this.relayed_by = transactionDict["relayed_by"].Value;
            }

            // out
            if (transactionDict["out"] != null)
            {
                JSONArray outArr = transactionDict["out"].AsArray;
                for (int i = 0; i < outArr.Count; i++)
                {
                    JSONObject     outObj = outArr[i].AsObject;
                    TransactionOut tOut   = new TransactionOut();

                    tOut.parseFromObj(outObj);
                    this.outTransactions.Add(tOut);
                }
            }

            if (transactionDict["lock_time"] != null)
            {
                this.lock_time = transactionDict["lock_time"].AsDouble;
            }

            if (transactionDict["size"] != null)
            {
                this.size = transactionDict["size"].AsInt;
            }

            if (transactionDict["rbf"] != null)
            {
                this.rbf = transactionDict["rbf"].AsBool;
            }

            if (transactionDict["double_spend"] != null)
            {
                this.double_spend = transactionDict["double_spend"].AsBool;
            }

            if (transactionDict["time"] != null)
            {
                this.time = transactionDict["time"].AsDouble;
            }

            if (transactionDict["tx_index"] != null)
            {
                this.tx_index = transactionDict["tx_index"].AsDouble;
            }

            if (transactionDict["vin_sz"] != null)
            {
                this.vin_sz = transactionDict["vin_sz"].AsInt;
            }

            if (transactionDict["hash"] != null)
            {
                this.hash = transactionDict["hash"].Value;
            }

            if (transactionDict["vout_sz"] != null)
            {
                this.vout_sz = transactionDict["vout_sz"].AsInt;
            }
        }