Ejemplo n.º 1
0
        public ActionResult GetDepositInvoice(string amount, string memo, string anon)
        {
            bool isAnon = !(anon == null || anon != "1");

            if (!isAnon && !User.Identity.IsAuthenticated)
            {
                // This is a user-related invoice, and no user is logged in.
                return(RedirectToAction("Login", "Account", new { returnUrl = Request.Url.ToString() }));
            }

            string userId;

            if (isAnon)
            {
                userId = null;
            }
            else
            {
                userId = User.Identity.GetUserId();
            }

            if (memo == null || memo == "")
            {
                memo = "Zapread.com";
            }

            var lndClient = new LndRpcClient(
                host: System.Configuration.ConfigurationManager.AppSettings["LnMainnetHost"],
                macaroonAdmin: System.Configuration.ConfigurationManager.AppSettings["LnMainnetMacaroonAdmin"],
                macaroonRead: System.Configuration.ConfigurationManager.AppSettings["LnMainnetMacaroonRead"],
                macaroonInvoice: System.Configuration.ConfigurationManager.AppSettings["LnMainnetMacaroonInvoice"]);

            var inv = lndClient.AddInvoice(Convert.ToInt64(amount), memo: memo, expiry: "432000");

            LnRequestInvoiceResponse resp = new LnRequestInvoiceResponse()
            {
                Invoice = inv.payment_request,
                Result  = "success",
            };

            //Create transaction record (not settled)
            using (ZapContext db = new ZapContext())
            {
                // TODO: ensure user exists?
                zapread.com.Models.User user = null;
                if (userId != null)
                {
                    user = db.Users.Where(u => u.AppId == userId).First();
                }

                //create a new transaction
                LNTransaction t = new LNTransaction()
                {
                    User             = user,
                    IsSettled        = false,
                    IsSpent          = false,
                    Memo             = memo,
                    Amount           = Convert.ToInt64(amount),
                    HashStr          = inv.r_hash,
                    IsDeposit        = true,
                    TimestampCreated = DateTime.Now,
                    PaymentRequest   = inv.payment_request,
                    UsedFor          = TransactionUse.UserDeposit,
                    UsedForId        = userId != null ? user.Id : -1,
                };
                db.LightningTransactions.Add(t);
                db.SaveChanges();
            }

            // If a listener is not already running, this should start
            // Check if there is one already online.
            var numListeners = lndTransactionListeners.Count(kvp => kvp.Value.IsLive);

            // If we don't have one running - start it and subscribe
            if (numListeners < 1)
            {
                var listener = lndClient.GetListener();
                lndTransactionListeners.TryAdd(listener.ListenerId, listener);           // keep alive while we wait for payment
                listener.InvoicePaid += NotifyClientsInvoicePaid;                        // handle payment message
                listener.StreamLost  += OnListenerLost;                                  // stream lost
                var a = new Task(() => listener.Start());                                // listen for payment
                a.Start();
            }

            return(Json(resp));
        }
Ejemplo n.º 2
0
        public async Task <ActionResult> Comment(Vote v)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { result = "error", message = "Invalid" }));
            }

            if (v.a < 1)
            {
                return(Json(new { result = "error", message = "Invalid" }));
            }

            var userId = User.Identity.GetUserId();

            using (var db = new ZapContext())
            {
                var comment = db.Comments
                              .Include(c => c.VotesUp)
                              .Include(c => c.VotesDown)
                              .Include(c => c.UserId)
                              .Include(c => c.UserId.Funds)
                              .Include(c => c.Post)
                              .FirstOrDefault(c => c.CommentId == v.Id);

                if (comment == null)
                {
                    return(Json(new { result = "error", message = "Invalid Comment" }));
                }

                zapread.com.Models.User user = null;

                if (userId == null) // Anonymous vote
                {
                    // Check if vote tx has been claimed
                    if (v.tx != -1337) //debugging secret
                    {
                        var vtx = db.LightningTransactions.FirstOrDefault(tx => tx.Id == v.tx);

                        if (vtx == null || vtx.IsSpent == true)
                        {
                            return(Json(new { result = "error", message = "No transaction to vote with" }));
                        }

                        vtx.IsSpent = true;
                        await db.SaveChangesAsync();
                    }
                }
                else
                {
                    user = db.Users
                           .Include(usr => usr.Funds)
                           .Include(usr => usr.EarningEvents)
                           .FirstOrDefault(u => u.AppId == userId);

                    if (user == null)
                    {
                        return(Json(new { result = "error", message = "Invalid User" }));
                    }

                    if (user.Funds.Balance < v.a)
                    {
                        return(Json(new { result = "error", message = "Insufficient Funds." }));
                    }

                    user.Funds.Balance -= v.a;
                }

                var spendingEvent = new SpendingEvent()
                {
                    Amount    = v.a,
                    Comment   = comment,
                    TimeStamp = DateTime.UtcNow,
                };

                double userBalance = 0.0;
                if (user != null)
                {
                    userBalance = user.Funds.Balance;
                    user.SpendingEvents.Add(spendingEvent);
                }

                if (v.d == 1)
                {
                    if (comment.VotesUp.Contains(user))
                    {
                        // Already voted
                    }
                    else if (user != null)
                    {
                        comment.VotesUp.Add(user);
                        user.CommentVotesUp.Add(comment);
                    }

                    comment.Score       += v.a;
                    comment.TotalEarned += 0.6 * v.a;

                    var ea = new Models.EarningEvent()
                    {
                        Amount     = 0.6 * v.a,
                        OriginType = 1, // Comment
                        TimeStamp  = DateTime.UtcNow,
                        Type       = 0, // Direct earning
                    };

                    var webratio = 0.1;
                    var comratio = 0.1;

                    var owner = comment.UserId;
                    if (owner != null)
                    {
                        owner.Reputation += v.a;
                        owner.EarningEvents.Add(ea);
                        owner.TotalEarned += 0.6 * v.a;
                        if (owner.Funds == null)
                        {
                            owner.Funds = new UserFunds()
                            {
                                Balance = 0.6 * v.a, TotalEarned = 0.6 * v.a
                            };
                        }
                        else
                        {
                            owner.Funds.Balance += 0.6 * v.a;
                        }
                    }

                    if (comment.Post != null)
                    {
                        var group = comment.Post.Group;
                        if (group != null)
                        {
                            group.TotalEarnedToDistribute += 0.2 * v.a;
                        }
                        else
                        {
                            // not in group - send to community
                            comratio += 0.2;
                        }
                    }
                    else
                    {
                        comratio += 0.2;
                    }

                    var website = db.ZapreadGlobals.FirstOrDefault(i => i.Id == 1);

                    if (website != null)
                    {
                        // Will be distributed to all users
                        website.CommunityEarnedToDistribute += comratio * v.a;

                        // And to the website
                        website.ZapReadTotalEarned   += webratio * v.a;
                        website.ZapReadEarnedBalance += webratio * v.a;
                    }
                    try
                    {
                        await db.SaveChangesAsync();
                    }
                    catch (Exception)
                    {
                        return(Json(new { result = "error", message = "Error" }));
                    }

                    return(Json(new { result = "success", delta = 1, score = comment.Score, balance = userBalance, scoreStr = comment.Score.ToAbbrString() }));
                }
                else
                {
                    if (comment.VotesDown.Contains(user))
                    {
                        // Already voted
                    }
                    else if (user != null)
                    {
                        comment.VotesDown.Add(user);
                        user.CommentVotesDown.Add(comment);
                    }
                    comment.Score -= v.a;

                    // Record and assign earnings
                    // Related to post owner
                    var webratio = 0.1;
                    var comratio = 0.1;

                    var owner = comment.UserId;
                    if (owner != null)
                    {
                        owner.Reputation -= v.a;
                    }

                    if (comment.Post != null)
                    {
                        var postGroup = comment.Post.Group;
                        if (postGroup != null)
                        {
                            postGroup.TotalEarnedToDistribute += 0.8 * v.a;
                        }
                        else
                        {
                            comratio += 0.8;
                        }
                    }
                    else
                    {
                        comratio += 0.8;
                    }

                    var website = db.ZapreadGlobals.FirstOrDefault(i => i.Id == 1);

                    if (website != null)
                    {
                        // Will be distributed to all users
                        website.CommunityEarnedToDistribute += comratio * v.a;

                        // And to the website
                        website.ZapReadTotalEarned   += webratio * v.a;
                        website.ZapReadEarnedBalance += webratio * v.a;
                    }

                    await db.SaveChangesAsync();

                    return(Json(new { result = "success", delta = -1, score = comment.Score, balance = userBalance, scoreStr = comment.Score.ToAbbrString() }));
                }
            }
        }