func (c *Controller) ChangeMoneyBackTime() (string, error) { txType := "ChangeMoneyBackTime" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() orderId := int64(utils.StrToFloat64(c.Parameters["order_id"])) days := int64(utils.StrToFloat64(c.Parameters["days"])) TemplateStr, err := makeTemplate("change_money_back_time", "changeMoneyBackTime", &changeMoneyBackTimePage{ Alert: c.Alert, Lang: c.Lang, ShowSignData: c.ShowSignData, SignData: "", UserId: c.SessUserId, OrderId: orderId, Days: days, CountSignArr: c.CountSignArr, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) EWithdraw() (string, error) { if c.SessUserId == 0 { return "", errors.New(c.Lang["sign_up_please"]) } c.r.ParseForm() currencyId := utils.StrToInt64(c.r.FormValue("currency_id")) if !utils.CheckInputData(c.r.FormValue("amount"), "amount") { return "", fmt.Errorf("incorrect amount") } method := c.r.FormValue("method") if !utils.CheckInputData(method, "method") { return "", fmt.Errorf("incorrect method") } account := c.r.FormValue("account") if !utils.CheckInputData(account, "account") { return "", fmt.Errorf("incorrect account") } amount := utils.StrToFloat64(c.r.FormValue("amount")) curTime := utils.Time() // нужно проверить, есть ли нужная сумма на счету юзера userAmount := utils.EUserAmountAndProfit(c.SessUserId, currencyId) if userAmount < amount { return "", fmt.Errorf("%s (%f<%f)", c.Lang["not_enough_money"], userAmount, amount) } if method != "Dcoin" && currencyId < 1000 { return "", fmt.Errorf("incorrect method") } err := userLock(c.SessUserId) if err != nil { return "", utils.ErrInfo(err) } err = c.ExecSql(`UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = ? AND currency_id = ?`, userAmount-amount, curTime, c.SessUserId, currencyId) if err != nil { return "", utils.ErrInfo(err) } var commission float64 if method == "Dcoin" { commission = utils.StrToFloat64(c.EConfig["dc_commission"]) } else if method == "Perfect-money" { commission = utils.StrToFloat64(c.EConfig["pm_commission"]) } wdAmount := utils.ClearNull(utils.Float64ToStr(amount*(1-commission/100)), 2) err = c.ExecSql(`INSERT INTO e_withdraw (open_time, user_id, currency_id, account, amount, wd_amount, method) VALUES (?, ?, ?, ?, ?, ?, ?)`, curTime, c.SessUserId, currencyId, account, amount, wdAmount, method) if err != nil { return "", utils.ErrInfo(err) } userUnlock(c.SessUserId) return utils.JsonAnswer(c.Lang["request_is_created"], "success").String(), nil }
func (c *Controller) ESaveOrder() (string, error) { if c.SessUserId == 0 { return "", errors.New(c.Lang["sign_up_please"]) } c.r.ParseForm() sellCurrencyId := utils.StrToInt64(c.r.FormValue("sell_currency_id")) buyCurrencyId := utils.StrToInt64(c.r.FormValue("buy_currency_id")) amount := utils.StrToFloat64(c.r.FormValue("amount")) sellRate := utils.StrToFloat64(c.r.FormValue("sell_rate")) orderType := c.r.FormValue("type") // можно ли торговать такими валютами checkCurrency, err := c.Single("SELECT count(id) FROM e_currency WHERE id IN (?, ?)", sellCurrencyId, buyCurrencyId).Int64() if err != nil { return "", utils.ErrInfo(err) } if checkCurrency != 2 { return "", errors.New("Currency error") } if orderType != "sell" && orderType != "buy" { return "", errors.New("Type error") } if amount == 0 { return "", errors.New(c.Lang["amount_error"]) } if amount < 0.001 && sellCurrencyId < 1000 { return "", errors.New(strings.Replace(c.Lang["save_order_min_amount"], "[amount]", "0.001", -1)) } if sellRate < 0.0001 { return "", errors.New(strings.Replace(c.Lang["save_order_min_price"], "[price]", "0.0001", -1)) } reductionLock, err := utils.EGetReductionLock() if err != nil { return "", utils.ErrInfo(err) } if reductionLock > 0 { return "", errors.New(strings.Replace(c.Lang["creating_orders_unavailable"], "[minutes]", "30", -1)) } // нужно проверить, есть ли нужная сумма на счету юзера userAmountAndProfit := utils.EUserAmountAndProfit(c.SessUserId, sellCurrencyId) if userAmountAndProfit < amount { return "", errors.New(c.Lang["not_enough_money"] + " (" + utils.Float64ToStr(userAmountAndProfit) + "<" + utils.Float64ToStr(amount) + ")" + strings.Replace(c.Lang["add_funds_link"], "[currency]", "USD", -1)) } err = NewForexOrder(c.SessUserId, amount, sellRate, sellCurrencyId, buyCurrencyId, orderType, utils.StrToMoney(c.EConfig["commission"])) if err != nil { return "", utils.ErrInfo(err) } else { return utils.JsonAnswer(c.Lang["order_created"], "success").String(), nil } return ``, nil }
func (c *Controller) SaveRaceCountry() (string, error) { if c.SessRestricted != 0 { return "", utils.ErrInfo(errors.New("Permission denied")) } c.r.ParseForm() race := int(utils.StrToFloat64(c.r.FormValue("race"))) country := int(utils.StrToFloat64(c.r.FormValue("country"))) err := c.ExecSql("UPDATE "+c.MyPrefix+"my_table SET race = ?, country = ?", race, country) if err != nil { return "", utils.ErrInfo(err) } return `{"error":"0"}`, nil }
func (c *Controller) EDelOrder() (string, error) { c.r.ParseForm() orderId := utils.StrToInt64(c.r.FormValue("order_id")) // возвращаем сумму ордера на кошелек + возращаем комиссию. order, err := utils.DB.OneRow("SELECT amount, sell_currency_id FROM e_orders WHERE id = ? AND user_id = ? AND del_time = 0 AND empty_time = 0", orderId, c.SessUserId).String() if err != nil { return "", utils.ErrInfo(err) } if len(order) == 0 { return "", utils.ErrInfo("order_id error") } sellCurrencyId := utils.StrToInt64(order["sell_currency_id"]) amount := utils.StrToFloat64(order["amount"]) amountAndCommission := utils.StrToFloat64(order["amount"]) / (1 - c.ECommission/100) // косиссия биржи commission := amountAndCommission - amount err = userLock(c.SessUserId) if err != nil { return "", err } // отмечаем, что ордер удален err = utils.DB.ExecSql("UPDATE e_orders SET del_time = ? WHERE id = ? AND user_id = ?", utils.Time(), orderId, c.SessUserId) if err != nil { return "", utils.ErrInfo(err) } // возвращаем остаток ордера на кошель userAmount := utils.EUserAmountAndProfit(c.SessUserId, sellCurrencyId) err = utils.DB.ExecSql("UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = ? AND currency_id = ?", userAmount+amountAndCommission, utils.Time(), c.SessUserId, sellCurrencyId) if err != nil { return "", utils.ErrInfo(err) } // вычитаем комиссию биржи userAmount = utils.EUserAmountAndProfit(1, sellCurrencyId) err = utils.DB.ExecSql("UPDATE e_wallets SET amount = ?, last_update = ? WHERE user_id = 1 AND currency_id = ?", userAmount-commission, utils.Time(), sellCurrencyId) if err != nil { return "", utils.ErrInfo(err) } userUnlock(c.SessUserId) return ``, nil }
func (c *Controller) DelCfProject() (string, error) { var err error txType := "DelCfProject" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() delId := int64(utils.StrToFloat64(c.Parameters["del_id"])) projectCurrencyName, err := c.Single("SELECT project_currency_name FROM cf_projects WHERE id = ?", delId).String() if err != nil { return "", utils.ErrInfo(err) } TemplateStr, err := makeTemplate("del_cf_project", "delCfProject", &DelCfProjectPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, SignData: fmt.Sprintf(`%d,%d,%d,%d`, txTypeId, timeNow, c.SessUserId, delId), UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, DelId: delId, ProjectCurrencyName: projectCurrencyName}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) RepaymentCredit() (string, error) { txType := "RepaymentCredit" txTypeId := utils.TypeInt(txType) timeNow := time.Now().Unix() creditId := utils.Round(utils.StrToFloat64(c.Parameters["credit_id"]), 0) TemplateStr, err := makeTemplate("repayment_credit", "repaymentCredit", &repaymentCreditPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, SignData: "", CreditId: creditId, CurrencyList: c.CurrencyList}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) ChangeCreditor() (string, error) { txType := "ChangeCreditor" txTypeId := utils.TypeInt(txType) timeNow := time.Now().Unix() creditId := utils.Round(utils.StrToFloat64(c.Parameters["credit_id"]), 0) log.Debug("creditId", creditId) TemplateStr, err := makeTemplate("change_creditor", "changeCreditor", &changeCreditorPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, SignData: "", CreditId: creditId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) MoneyBackRequest() (string, error) { txType := "MoneyBackRequest" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() orderId := int64(utils.StrToFloat64(c.Parameters["order_id"])) order, err := c.OneRow("SELECT * FROM orders WHERE id = ?", orderId).String() if err != nil { return "", utils.ErrInfo(err) } TemplateStr, err := makeTemplate("money_back_request", "moneyBackRequest", &moneyBackRequestPage{ Alert: c.Alert, Lang: c.Lang, ShowSignData: c.ShowSignData, SignData: "", UserId: c.SessUserId, OrderId: orderId, Order: order, CountSignArr: c.CountSignArr, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) DelCfFunding() (string, error) { var err error txType := "DelCfFunding" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() delId := int64(utils.StrToFloat64(c.Parameters["del_id"])) TemplateStr, err := makeTemplate("del_cf_funding", "delCfFunding", &DelCfFundingPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, SignData: fmt.Sprintf(`%d,%d,%d,%d`, txTypeId, timeNow, c.SessUserId, delId), UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, DelId: delId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) MiningPromisedAmount() (string, error) { txType := "Mining" txTypeId := utils.TypeInt(txType) timeNow := time.Now().Unix() amount := utils.StrToMoney(c.Parameters["amount"]) amount = math.Floor(amount*100) / 100 promisedAmountId := int64(utils.StrToFloat64(c.Parameters["promised_amount_id"])) log.Debug("c.Parameters[promised_amount_id]):", c.Parameters["promised_amount_id"]) log.Debug("promisedAmountId:", promisedAmountId) TemplateStr, err := makeTemplate("mining_promised_amount", "miningPromisedAmount", &miningPromisedAmountPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, SignData: fmt.Sprintf("%v,%v,%v,%v,%v", txTypeId, timeNow, c.SessUserId, promisedAmountId, amount), Amount: amount, PromisedAmountId: promisedAmountId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) ChangePromisedAmount() (string, error) { txType := "ChangePromisedAmount" txTypeId := utils.TypeInt(txType) timeNow := time.Now().Unix() promisedAmountId := int64(utils.StrToFloat64(c.Parameters["promised_amount_id"])) amount := c.Parameters["amount"] TemplateStr, err := makeTemplate("change_promised_amount", "changePromisedAmount", &changePromisedAmountPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, SignData: fmt.Sprintf("%v,%v,%v,%v,%v", txTypeId, timeNow, c.SessUserId, promisedAmountId, amount), PromisedAmountId: promisedAmountId, Amount: amount}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) NewPhoto() (string, error) { c.r.ParseForm() userId := int64(utils.StrToFloat64(c.r.FormValue("user_id"))) data, err := c.OneRow("SELECT photo_block_id, photo_max_miner_id, miners_keepers FROM miners_data WHERE user_id = ?", userId).String() if err != nil { return "", utils.ErrInfo(err) } // получим ID майнеров, у которых лежат фото нужного нам юзера minersIds := utils.GetMinersKeepers(data["photo_block_id"], data["photo_max_miner_id"], data["miners_keepers"], true) // берем 1 случайный из 10-и ID майнеров k := utils.RandInt(0, len(minersIds)) minerId := minersIds[k] host, err := c.Single("SELECT http_host FROM miners_data WHERE miner_id = ?", minerId).String() if err != nil { return "", utils.ErrInfo(err) } result, err := json.Marshal(map[string]string{"face": host + "public/face_" + utils.Int64ToStr(userId) + ".jpg", "profile": host + "public/profile_" + utils.Int64ToStr(userId) + ".jpg"}) if err != nil { return "", utils.ErrInfo(err) } return string(result), nil }
func (c *Controller) AddCfProjectData() (string, error) { var err error txType := "CfProjectData" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() projectId := int64(utils.StrToFloat64(c.Parameters["projectId"])) id := int64(utils.StrToFloat64(c.Parameters["id"])) cfData := make(map[string]string) if id > 0 { log.Debug("id:", id) cfData, err = c.OneRow("SELECT * FROM cf_projects_data WHERE id = ?", id).String() if err != nil { return "", utils.ErrInfo(err) } projectId = utils.StrToInt64(cfData["project_id"]) } cfCurrencyName, err := c.Single("SELECT project_currency_name FROM cf_projects WHERE id = ?", projectId).String() if err != nil { return "", utils.ErrInfo(err) } CfLng, err := c.GetAllCfLng() log.Debug("CfData", cfData) TemplateStr, err := makeTemplate("add_cf_project_data", "addCfProjectData", &AddCfProjectDataPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, ProjectId: projectId, Id: id, CfData: cfData, CfCurrencyName: cfCurrencyName, CfLng: CfLng}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) CfCatalog() (string, error) { var err error log.Debug("CfCatalog") categoryId := utils.Int64ToStr(int64(utils.StrToFloat64(c.Parameters["category_id"]))) log.Debug("categoryId", categoryId) var curCategory string addSql := "" if categoryId != "0" { addSql = `AND category_id = ` + categoryId curCategory = c.Lang["cf_category_"+categoryId] } cfUrl := "" projects := make(map[string]map[string]string) cfProjects, err := c.GetAll(` SELECT cf_projects.id, lang_id, blurb_img, country, city, currency_id, end_time, amount FROM cf_projects LEFT JOIN cf_projects_data ON cf_projects_data.project_id = cf_projects.id WHERE del_block_id = 0 AND end_time > ? AND lang_id = ? `+addSql+` ORDER BY funders DESC LIMIT 100 `, 100, utils.Time(), c.LangInt) if err != nil { return "", utils.ErrInfo(err) } for _, data := range cfProjects { CfProjectData, err := c.GetCfProjectData(utils.StrToInt64(data["id"]), utils.StrToInt64(data["end_time"]), c.LangInt, utils.StrToFloat64(data["amount"]), cfUrl) if err != nil { return "", utils.ErrInfo(err) } for k, v := range CfProjectData { data[k] = v } projects[data["id"]] = data } cfCategory := utils.MakeCfCategories(c.Lang) TemplateStr, err := makeTemplate("cf_catalog", "cfCatalog", &cfCatalogPage{ Lang: c.Lang, CfCategory: cfCategory, CurrencyList: c.CurrencyList, CurCategory: curCategory, Projects: projects, UserId: c.SessUserId, CategoryId: categoryId, CfUrl: cfUrl}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) EGateIk() (string, error) { c.r.ParseForm() fmt.Println(c.r.Form) var ikNames []string for name, _ := range c.r.Form { if name[:2] == "ik" && name != "ik_sign" { ikNames = append(ikNames, name) } } sort.Strings(ikNames) fmt.Println(ikNames) var ikValues []string for _, names := range ikNames { ikValues = append(ikValues, c.r.FormValue(names)) } ikValues = append(ikValues, c.EConfig["ik_s_key"]) fmt.Println(ikValues) sign := strings.Join(ikValues, ":") fmt.Println(sign) sign = base64.StdEncoding.EncodeToString(utils.HexToBin(utils.Md5(sign))) fmt.Println(sign) if sign != c.r.FormValue("ik_sign") { return "", errors.New("Incorrect signature") } currencyId := int64(0) if c.r.FormValue("ik_cur") == "USD" { currencyId = 1001 } if currencyId == 0 { return "", errors.New("Incorrect currencyId") } amount := utils.StrToFloat64(c.r.FormValue("ik_am")) pmId := utils.StrToInt64(c.r.FormValue("ik_inv_id")) // проверим, не зачисляли ли мы уже это платеж existsId, err := c.Single(`SELECT id FROM e_adding_funds_ik WHERE id = ?`, pmId).Int64() if err != nil { return "", utils.ErrInfo(err) } if existsId != 0 { return "", errors.New("Incorrect ik_inv_id") } paymentInfo := c.r.FormValue("ik_desc") txTime := utils.Time() err = EPayment(paymentInfo, currencyId, txTime, amount, pmId, "ik", c.ECommission) if err != nil { return "", utils.ErrInfo(err) } return ``, nil }
func (c *Controller) SaveGeolocation() (string, error) { if c.SessRestricted != 0 { return "", utils.ErrInfo(errors.New("Permission denied")) } c.r.ParseForm() geolocation := c.r.FormValue("geolocation") if len(geolocation) > 0 { x := strings.Split(geolocation, ", ") if len(x) == 2 { geolocationLat := utils.Round(utils.StrToFloat64(x[0]), 5) geolocationLon := utils.Round(utils.StrToFloat64(x[1]), 5) err := c.ExecSql("UPDATE "+c.MyPrefix+"my_table SET geolocation = ?", utils.Float64ToStrGeo(geolocationLat)+", "+utils.Float64ToStrGeo(geolocationLon)) if err != nil { return "", utils.ErrInfo(err) } } } return `{"error":"0"}`, nil }
func (c *Controller) MoneyBack() (string, error) { txType := "MoneyBack" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() orderId := int64(utils.StrToFloat64(c.Parameters["order_id"])) amount := utils.StrToFloat64(c.Parameters["amount"]) arbitrator := int64(utils.StrToFloat64(c.Parameters["arbitrator"])) var li, redirect string if arbitrator > 0 { li = `<li><a href="#arbitrationArbitrator">` + c.Lang["i_arbitrator"] + `</a></li>` redirect = `arbitrationArbitrator` } else { li = `<li><a href="#arbitrationArbitrator">` + c.Lang["i_seller"] + `</a></li>` redirect = `arbitrationSeller` } TemplateStr, err := makeTemplate("money_back", "moneyBack", &moneyBackPage{ Alert: c.Alert, Lang: c.Lang, ShowSignData: c.ShowSignData, SignData: "", UserId: c.SessUserId, OrderId: orderId, Amount: amount, Arbitrator: arbitrator, Li: li, Redirect: redirect, CountSignArr: c.CountSignArr, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) EGatePayeer() (string, error) { c.r.ParseForm() fmt.Println(c.r.Form) if utils.IPwoPort(c.r.RemoteAddr) != "37.59.221.23" { return "", errors.New("Incorrect RemoteAddr " + utils.IPwoPort(c.r.RemoteAddr)) } if len(c.r.FormValue("m_operation_id")) > 0 && len(c.r.FormValue("m_sign")) > 0 { sign := strings.ToUpper(string(utils.Sha256(c.r.FormValue("m_operation_id") + ":" + c.r.FormValue("m_operation_ps") + ":" + c.r.FormValue("m_operation_date") + ":" + c.r.FormValue("m_operation_pay_date") + ":" + c.r.FormValue("m_shop") + ":" + c.r.FormValue("m_orderid") + ":" + c.r.FormValue("m_amount") + ":" + c.r.FormValue("m_curr") + ":" + base64.StdEncoding.EncodeToString([]byte(c.r.FormValue("m_desc"))) + ":" + c.r.FormValue("m_status") + ":" + c.EConfig["payeer_s_key"]))) if c.r.FormValue("m_sign") == sign && c.r.FormValue("m_status") == "success" { txTime := utils.Time() currencyId := int64(0) if c.r.FormValue("m_curr") == "USD" { currencyId = 1001 } if currencyId == 0 { return c.r.FormValue("m_orderid") + "|success", nil } amount := utils.StrToFloat64(c.r.FormValue("m_amount")) pmId := utils.StrToInt64(c.r.FormValue("m_operation_id")) // проверим, не зачисляли ли мы уже это платеж existsId, err := c.Single(`SELECT id FROM e_adding_funds_payeer WHERE id = ?`, pmId).Int64() if err != nil { return c.r.FormValue("m_orderid") + "|success", nil } if existsId != 0 { return c.r.FormValue("m_orderid") + "|success", nil } paymentInfo := c.r.FormValue("m_desc") EPayment(paymentInfo, currencyId, txTime, amount, pmId, "payeer", c.ECommission) return c.r.FormValue("m_orderid") + "|success", nil } } return c.r.FormValue("m_orderid") + "|error", nil }
func (c *Controller) Profile() (string, error) { c.r.ParseForm() userId := int64(utils.StrToFloat64(c.r.FormValue("user_id"))) // получаем кол-во TDC на обещанных суммах rows, err := c.Query(c.FormatQuery(` SELECT from_user_id, time, comment FROM abuses WHERE user_id = ? `), userId) if err != nil { return "", utils.ErrInfo(err) } abuses := "" defer rows.Close() for rows.Next() { var from_user_id, abusestime int64 var comment string err = rows.Scan(&from_user_id, &abusestime, &comment) if err != nil { return "", utils.ErrInfo(err) } t := time.Unix(abusestime, 0) abuses += fmt.Sprintf("from_user_id: %d; time: %s; comment: %s<br>", from_user_id, t.Format(c.TimeFormat), comment) } if len(abuses) == 0 { abuses = "No" } regTime, err := c.Single("SELECT reg_time FROM miners_data WHERE user_id = ?", userId).Int64() if err != nil { return "", utils.ErrInfo(err) } t := time.Unix(regTime, 0) result, err := json.Marshal(map[string]string{"abuses": abuses, "reg_time": t.Format(c.TimeFormat)}) if err != nil { return "", utils.ErrInfo(err) } return string(result), nil }
func (c *Controller) EGatePm() (string, error) { c.r.ParseForm() fmt.Println(c.r.Form) sign := strings.ToUpper(string(utils.Md5(c.r.FormValue("PAYMENT_ID") + ":" + c.r.FormValue("PAYEE_ACCOUNT") + ":" + c.r.FormValue("PAYMENT_AMOUNT") + ":" + c.r.FormValue("PAYMENT_UNITS") + ":" + c.r.FormValue("PAYMENT_BATCH_NUM") + ":" + c.r.FormValue("PAYER_ACCOUNT") + ":" + strings.ToUpper(string(utils.Md5(c.EConfig["pm_s_key"]))) + ":" + c.r.FormValue("TIMESTAMPGMT")))) txTime := utils.StrToInt64(c.r.FormValue("TIMESTAMPGMT")) if sign != c.r.FormValue("V2_HASH") { return "", errors.New("Incorrect signature") } currencyId := int64(0) if c.r.FormValue("PAYMENT_UNITS") == "USD" { currencyId = 1001 } if currencyId == 0 { return "", errors.New("Incorrect currencyId") } amount := utils.StrToFloat64(c.r.FormValue("PAYMENT_AMOUNT")) pmId := utils.StrToInt64(c.r.FormValue("PAYMENT_BATCH_NUM")) // проверим, не зачисляли ли мы уже это платеж existsId, err := c.Single(`SELECT id FROM e_adding_funds_pm WHERE id = ?`, pmId).Int64() if err != nil { return "", utils.ErrInfo(err) } if existsId != 0 { return "", errors.New("Incorrect PAYMENT_BATCH_NUM") } paymentInfo := c.r.FormValue("PAYMENT_ID") err = EPayment(paymentInfo, currencyId, txTime, amount, pmId, "pm", c.ECommission) if err != nil { return "", utils.ErrInfo(err) } return ``, nil }
func (c *Controller) GetBlock() (string, error) { c.r.ParseForm() BlockId := int64(utils.StrToFloat64(c.r.FormValue("id"))) if BlockId == 0 { return `{"error": "nil id"}`, nil } if len(c.r.FormValue("download")) > 0 { c.w.Header().Set("Content-type", "application/octet-stream") c.w.Header().Set("Content-Disposition", "attachment; filename=\""+utils.Int64ToStr(BlockId)+".binary\"") } block, err := c.Single("SELECT data FROM block_chain WHERE id = ?", BlockId).String() if err != nil { return "", utils.ErrInfo(err) } return block, nil }
func (c *Controller) PoolAdminLogin() (string, error) { if !c.PoolAdmin { return "", utils.ErrInfo(errors.New("access denied")) } c.r.ParseForm() userId := int64(utils.StrToFloat64(c.Parameters["userId"])) publicKey, err := c.GetUserPublicKey(userId) if err != nil { return "", utils.ErrInfo(err) } c.sess.Set("user_id", userId) c.sess.Set("public_key", string(utils.BinToHex(publicKey))) TemplateStr, err := makeTemplate("pool_admin_login", "poolAdminLogin", &poolAdminPage{}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) getMyWallets() ([]map[string]string, error) { var myWallets []map[string]string eCurrency, err := c.GetAll(`SELECT name as currency_name, id FROM e_currency ORDER BY sort_id ASC`, -1) if err != nil { return myWallets, utils.ErrInfo(err) } for _, data := range eCurrency { wallet, err := c.OneRow("SELECT * FROM e_wallets WHERE user_id = ? AND currency_id = ?", c.SessUserId, data["id"]).String() if err != nil { return myWallets, utils.ErrInfo(err) } if len(wallet) > 0 { amount := utils.StrToFloat64(wallet["amount"]) profit, err := utils.DB.CalcProfitGen(utils.StrToInt64(wallet["currency_id"]), amount, 0, utils.StrToInt64(wallet["last_update"]), utils.Time(), "wallet") if err != nil { return myWallets, utils.ErrInfo(err) } myWallets = append(myWallets, map[string]string{"amount": utils.ClearNull(utils.Float64ToStr(amount+profit), 2), "currency_name": data["currency_name"], "last_update": wallet["last_update"]}) } } return myWallets, nil }
func (c *Controller) CfProjectChangeCategory() (string, error) { var err error txType := "CfProjectData" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() projectId := int64(utils.StrToFloat64(c.Parameters["project_id"])) data, err := c.OneRow("SELECT category_id, project_currency_name FROM cf_projects WHERE id= ?", projectId).String() if err != nil { return "", utils.ErrInfo(err) } categoryId := data["category_id"] projectCurrencyName := data["project_currency_name"] cfCategory := utils.MakeCfCategories(c.Lang) TemplateStr, err := makeTemplate("cf_project_change_category", "cfProjectChangeCategory", &cfProjectChangeCategoryPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, SignData: fmt.Sprintf(`%d,%d,%d,%d`, txTypeId, timeNow, c.SessUserId, categoryId), UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, ProjectId: projectId, CategoryId: categoryId, CfCategory: cfCategory, ProjectCurrencyName: projectCurrencyName}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) BugReporting() (string, error) { txType := "MessageToAdmin" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() if c.SessRestricted != 0 { return "", utils.ErrInfo(errors.New("Permission denied")) } // если юзер тыкнул по какой-то ветке сообщений, то тут будет parent_id, т.е. id этой ветки parentId := int64(utils.StrToFloat64(c.Parameters["parent_id"])) messages, err := c.GetAll(` SELECT * FROM `+c.MyPrefix+`my_admin_messages WHERE message_type = 0 AND (parent_id = ? OR id = ?) ORDER BY id DESC `, -1, parentId, parentId) TemplateStr, err := makeTemplate("bug_reporting", "bugReporting", &bugReportingPage{ Alert: c.Alert, Lang: c.Lang, ShowSignData: c.ShowSignData, SignData: "", UserId: c.SessUserId, ParentId: parentId, Messages: messages, CountSignArr: c.CountSignArr, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (p *Parser) SendDcFront() error { err := p.generalCheck() if err != nil { return p.ErrInfo(err) } verifyData := map[string]string{"from_user_id": "bigint", "to_user_id": "bigint", "currency_id": "bigint", "amount": "amount", "commission": "amount", "comment": "comment"} err = p.CheckInputData(verifyData) if err != nil { return p.ErrInfo(err) } if p.TxMaps.Float64["amount"] < 0.01 { // 0.01 - минимальная сумма return p.ErrInfo("amount") } // проверим, существует ли такая валюта в таблиуе DC-валют checkCurrency, err := p.CheckCurrency(p.TxMaps.Int64["currency_id"]) if !checkCurrency { // если нет, то проверяем список CF-валют checkCurrency, err := p.CheckCurrencyCF(p.TxMaps.Int64["currency_id"]) if err != nil { return p.ErrInfo(err) } if !checkCurrency { return p.ErrInfo("currency_id") } } nodeCommission, err := p.getMyNodeCommission(p.TxMaps.Int64["currency_id"], p.TxUserID, p.TxMaps.Float64["amount"]) if err != nil { return p.ErrInfo(err) } // проверим, удовлетворяет ли нас комиссия, которую предлагает юзер if p.TxMaps.Float64["commission"] < nodeCommission { return p.ErrInfo(fmt.Sprintf("commission %v<%v", p.TxMaps.Float64["commission"], nodeCommission)) } if p.BlockData != nil && p.BlockData.BlockId <= consts.ARBITRATION_BLOCK_START { for i := 0; i < 5; i++ { p.TxMaps.Float64["arbitrator"+utils.IntToStr(i)+"_commission"] = 0 // для check_sender_money } forSign := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s", p.TxMap["type"], p.TxMap["time"], p.TxMap["user_id"], p.TxMap["to_user_id"], p.TxMap["amount"], p.TxMap["commission"], utils.BinToHex(p.TxMap["comment"]), p.TxMap["currency_id"]) CheckSignResult, err := utils.CheckSign(p.PublicKeys, forSign, p.TxMap["sign"], false) if err != nil { return p.ErrInfo(err) } if !CheckSignResult { return p.ErrInfo("incorrect sign") } } else { dupArray := make(map[int64]int64) for i := 0; i < 5; i++ { arbitrator__commission := "arbitrator" + utils.IntToStr(i) + "_commission" arbitrator_ := "arbitrator" + utils.IntToStr(i) if !utils.CheckInputData(p.TxMap[arbitrator__commission], "amount") { return p.ErrInfo("arbitrator_commission") } if !utils.CheckInputData(p.TxMap[arbitrator_], "bigint") { return p.ErrInfo("arbitrator") } // если указал ID арбитра, то должна быть комиссия для него if p.TxMaps.Int64[arbitrator_] > 0 && p.TxMaps.Float64[arbitrator__commission] < 0.01 { return p.ErrInfo("arbitrator_commission") } // на всяк случай не даем арбитрам возможность быть арбитрами самим себе if p.TxMaps.Int64[arbitrator_] == p.TxUserID { return p.ErrInfo("arbitrator = user_id") } if p.TxMaps.Int64[arbitrator_] > 0 { dupArray[utils.BytesToInt64(p.TxMap[arbitrator_])]++ if dupArray[utils.BytesToInt64(p.TxMap[arbitrator_])] > 1 { return p.ErrInfo("doubles") } } if p.TxMaps.Int64[arbitrator_] > 0 { arbitrator := p.TxMap[arbitrator_] // проверим, является ли арбитром указанный user_id arbitratorConditionsJson, err := p.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id = ?", utils.BytesToInt64(arbitrator)).Bytes() if err != nil { return p.ErrInfo(err) } arbitratorConditionsMap := make(map[string][5]string) err = json.Unmarshal(arbitratorConditionsJson, &arbitratorConditionsMap) // арбитр к этому моменту мог передумать и убрать свои условия, уйдя из арбитров для новых сделок поставив [0] что вызовет тут ошибку if err != nil { log.Debug("arbitratorConditionsJson", arbitratorConditionsJson) return p.ErrInfo(err) } // проверим, работает ли выбранный арбитр с валютой данной сделки var checkCurrency int64 if p.TxMaps.Int64["currency_id"] > 1000 { checkCurrency = 1000 } else { checkCurrency = p.TxMaps.Int64["currency_id"] } if len(arbitratorConditionsMap[utils.Int64ToStr(checkCurrency)]) == 0 { return p.ErrInfo("len(arbitratorConditionsMap[checkCurrency]) == 0") } // указан ли этот арбитр в списке доверенных у продавца sellerArbitrator, err := p.Single("SELECT user_id FROM arbitration_trust_list WHERE user_id = ? AND arbitrator_user_id = ?", p.TxMaps.Int64["to_user_id"], utils.BytesToInt64(arbitrator)).Int64() if err != nil { return p.ErrInfo(err) } if sellerArbitrator == 0 { return p.ErrInfo("sellerArbitrator == 0") } // указан ли этот арбитр в списке доверенных у покупателя buyerArbitrator, err := p.Single("SELECT user_id FROM arbitration_trust_list WHERE user_id = ? AND arbitrator_user_id = ?", p.TxMaps.Int64["from_user_id"], utils.BytesToInt64(arbitrator)).Int64() if err != nil { return p.ErrInfo(err) } if buyerArbitrator == 0 { return p.ErrInfo("buyerArbitrator == 0") } // согласен ли продавец на манибек arbitrationDaysRefund, err := p.Single("SELECT arbitration_days_refund FROM users WHERE user_id = ?", p.TxMaps.Int64["to_user_id"]).Int64() if err != nil { return p.ErrInfo(err) } if arbitrationDaysRefund == 0 { return p.ErrInfo("buyerArbitrator == 0") } // готов ли арбитр рассматривать такую сумму сделки currencyIdStr := utils.Int64ToStr(p.TxMaps.Int64["currency_id"]) if p.TxMaps.Float64["amount"] < utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][0]) || (p.TxMaps.Float64["amount"] > utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][1]) && utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][1]) > 0) { return p.ErrInfo("amount") } // мин. комиссия, на которую согласен арбитр minArbitratorCommission := utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][4]) / 100 * p.TxMaps.Float64["amount"] if minArbitratorCommission > utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) && utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) > 0 { minArbitratorCommission = utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) } if minArbitratorCommission < utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][2]) { minArbitratorCommission = utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][2]) } if utils.BytesToFloat64(p.TxMap[arbitrator__commission]) < minArbitratorCommission { return p.ErrInfo(" < minArbitratorCommission") } } } forSign := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", p.TxMap["type"], p.TxMap["time"], p.TxMap["user_id"], p.TxMap["to_user_id"], p.TxMap["amount"], p.TxMap["commission"], p.TxMap["arbitrator0"], p.TxMap["arbitrator1"], p.TxMap["arbitrator2"], p.TxMap["arbitrator3"], p.TxMap["arbitrator4"], p.TxMap["arbitrator0_commission"], p.TxMap["arbitrator1_commission"], p.TxMap["arbitrator2_commission"], p.TxMap["arbitrator3_commission"], p.TxMap["arbitrator4_commission"], utils.BinToHex(p.TxMap["comment"]), p.TxMap["currency_id"]) CheckSignResult, err := utils.CheckSign(p.PublicKeys, forSign, p.TxMap["sign"], false) if err != nil { return p.ErrInfo(err) } if !CheckSignResult { return p.ErrInfo("incorrect sign") } } /* wallets_buffer сделан не для защиты от двойной траты, а для того, чтобы нода, которая генерит блок не записала двойное списание в свой блок, который будет отправлен другим нодам и будет ими отвергнут. Для тр-ий типа new_forex_order используется простой запрет на запись в блок тр-ии new_forex_order+new_forex_order или new_forex_order+send_dc и пр. защита от двойного списания на основе даннных из блока, полученного из сети заключается в постепенной обработке тр-ий путем проверки front_ и занесения данных в БД (ParseDataFull). */ amountAndCommission, err := p.checkSenderMoney(p.TxMaps.Int64["currency_id"], p.TxMaps.Int64["from_user_id"], p.TxMaps.Float64["amount"], p.TxMaps.Float64["commission"], p.TxMaps.Float64["arbitrator0_commission"], p.TxMaps.Float64["arbitrator1_commission"], p.TxMaps.Float64["arbitrator2_commission"], p.TxMaps.Float64["arbitrator3_commission"], p.TxMaps.Float64["arbitrator4_commission"]) if err != nil { return p.ErrInfo(err) } // существует ли юзер-получатель err = p.CheckUser(p.TxMaps.Int64["to_user_id"]) if err != nil { return p.ErrInfo(err) } err = p.checkSpamMoney(p.TxMaps.Int64["currency_id"], p.TxMaps.Float64["amount"]) if err != nil { return p.ErrInfo(err) } // вычитаем из wallets_buffer // amount_and_commission взято из check_sender_money() err = p.updateWalletsBuffer(amountAndCommission, p.TxMaps.Int64["currency_id"]) if err != nil { return p.ErrInfo(err) } return nil }
func (c *Controller) WalletsList() (string, error) { var err error // валюты currencyList := c.CurrencyListCf confirmedBlockId := c.ConfirmedBlockId var wallets []utils.DCAmounts var myDcTransactions []map[string]string if c.SessUserId > 0 { wallets, err = c.GetBalances(c.SessUserId) if c.SessRestricted == 0 { myDcTransactions, err = c.GetAll("SELECT * FROM "+c.MyPrefix+"my_dc_transactions ORDER BY id DESC LIMIT 100", 100) if err != nil { return "", utils.ErrInfo(err) } for id, data := range myDcTransactions { t := time.Unix(utils.StrToInt64(data["time"]), 0) timeFormatted := t.Format(c.TimeFormat) log.Debug("timeFormatted", utils.StrToInt64(data["time"]), timeFormatted, c.TimeFormat) myDcTransactions[id]["timeFormatted"] = timeFormatted myDcTransactions[id]["numBlocks"] = "0" blockId := utils.StrToInt64(data["block_id"]) if blockId > 0 { myDcTransactions[id]["numBlocks"] = utils.Int64ToStr(confirmedBlockId - blockId) } } } } userType := "SendDc" projectType := "CfSendDc" userTypeId := utils.TypeInt(userType) projectTypeId := utils.TypeInt(projectType) timeNow := time.Now().Unix() currentBlockId, err := c.GetBlockId() if err != nil { return "", utils.ErrInfo(err) } names := make(map[string]string) names["cash_request"] = c.Lang["cash"] names["from_mining_id"] = c.Lang["from_mining"] names["from_repaid"] = c.Lang["from_repaid_mining"] names["from_user"] = c.Lang["from_user"] names["node_commission"] = c.Lang["node_commission"] names["system_commission"] = c.Lang["system_commission"] names["referral"] = c.Lang["referral"] names["cf_project"] = "Crowd funding" names["cf_project_refund"] = "Crowd funding refund" minerId, err := c.GetMinerId(c.SessUserId) if err != nil { return "", utils.ErrInfo(err) } c.r.ParseForm() // если юзер кликнул по кнопку "профинансировать" со страницы проекта //parameters := c.r.FormValue("parameters") cfProjectId := int64(utils.StrToFloat64(c.Parameters["projectId"])) last_tx, err := c.GetLastTx(c.SessUserId, utils.TypesToIds([]string{"SendDc"}), 1, c.TimeFormat) lastTxFormatted := "" if len(last_tx) > 0 { lastTxFormatted, _ = utils.MakeLastTx(last_tx, c.Lang) } arbitrationTrustList_, err := c.GetMap(` SELECT arbitrator_user_id, conditions FROM arbitration_trust_list LEFT JOIN arbitrator_conditions ON arbitrator_conditions.user_id = arbitration_trust_list.arbitrator_user_id WHERE arbitration_trust_list.user_id = ? `, "arbitrator_user_id", "conditions", c.SessUserId) if err != nil { return "", utils.ErrInfo(err) } arbitrationTrustList := make(map[int64]map[int64][]string) var jsonMap map[string][]string for arbitrator_user_id, conditions := range arbitrationTrustList_ { err = json.Unmarshal([]byte(conditions), &jsonMap) if err != nil { return "", utils.ErrInfo(err) } uidInt := utils.StrToInt64(arbitrator_user_id) arbitrationTrustList[uidInt] = make(map[int64][]string) for currenycId, data := range jsonMap { arbitrationTrustList[uidInt][utils.StrToInt64(currenycId)] = data } } log.Debug("arbitrationTrustList", arbitrationTrustList) TemplateStr, err := makeTemplate("wallets_list", "walletsList", &walletsListPage{ CountSignArr: c.CountSignArr, CfProjectId: cfProjectId, Names: names, UserIdStr: utils.Int64ToStr(c.SessUserId), Alert: c.Alert, Community: c.Community, ConfigCommission: c.ConfigCommission, ProjectType: projectType, UserType: userType, UserId: c.SessUserId, Lang: c.Lang, CurrencyList: currencyList, Wallets: wallets, MyDcTransactions: myDcTransactions, UserTypeId: userTypeId, ProjectTypeId: projectTypeId, Time: timeNow, CurrentBlockId: currentBlockId, ConfirmedBlockId: confirmedBlockId, MinerId: minerId, Config: c.NodeConfig, LastTxFormatted: lastTxFormatted, ArbitrationTrustList: arbitrationTrustList, ShowSignData: c.ShowSignData, SignData: ""}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) MyCfProjects() (string, error) { var err error txType := "NewCfProject" txTypeId := utils.TypeInt(txType) timeNow := utils.Time() projectsLang := make(map[string]map[string]string) projects := make(map[string]map[string]string) cfProjects, err := c.GetAll(` SELECT id, category_id, project_currency_name, country, city, currency_id, end_time, amount FROM cf_projects WHERE user_id = ? AND del_block_id = 0 `, -1, c.SessUserId) if err != nil { return "", utils.ErrInfo(err) } for _, data := range cfProjects { CfProjectData, err := c.GetCfProjectData(utils.StrToInt64(data["id"]), utils.StrToInt64(data["end_time"]), c.LangInt, utils.StrToFloat64(data["amount"]), "") if err != nil { return "", utils.ErrInfo(err) } for k, v := range CfProjectData { data[k] = v } projects[data["id"]] = data lang, err := c.GetMap(`SELECT id, lang_id FROM cf_projects_data WHERE project_id = ?`, "id", "lang_id", data["id"]) projectsLang[data["id"]] = lang } cfLng, err := c.GetAllCfLng() TemplateStr, err := makeTemplate("my_cf_projects", "myCfProjects", &MyCfProjectsPage{ Alert: c.Alert, Lang: c.Lang, CountSignArr: c.CountSignArr, ShowSignData: c.ShowSignData, UserId: c.SessUserId, TimeNow: timeNow, TxType: txType, TxTypeId: txTypeId, CfLng: cfLng, CurrencyList: c.CurrencyList, Projects: projects, ProjectsLang: projectsLang}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }
func (c *Controller) BlockExplorer() (string, error) { var err error blockId := int64(utils.StrToFloat64(c.Parameters["blockId"])) start := int64(utils.StrToFloat64(c.Parameters["start"])) var data, sql string if start > 0 || (start == 0 && blockId == 0) { if start == 0 && blockId == 0 { data += "<h3>Latest Blocks</h3>" sql = ` SELECT data, hash FROM block_chain ORDER BY id DESC LIMIT 15` } else { sql = ` SELECT data, hash FROM block_chain ORDER BY id ASC LIMIT ` + utils.Int64ToStr(start-1) + `, 100` } data += `<table class="table"><tr><th>Block</th><th>Hash</th><th>Time</th><th><nobr>User id</nobr></th><th><nobr>Miner id</nobr></th><th>Level</th><th>Transactions</th></tr>` blocksChain, err := c.GetAll(sql, -1) if err != nil { return "", utils.ErrInfo(err) } for _, blockData := range blocksChain { hash := utils.BinToHex([]byte(blockData["hash"])) binaryData := []byte(blockData["data"]) parser := new(dcparser.Parser) parser.DCDB = c.DCDB parser.BinaryData = binaryData err = parser.ParseDataLite() parser.BlockData.Sign = utils.BinToHex(parser.BlockData.Sign) minerId, err := c.GetMinerId(parser.BlockData.UserId) if err != nil { return "", utils.ErrInfo(err) } data += fmt.Sprintf(`<tr><td><a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">%d</a></td><td>%s</td><td><nobr><span class='unixtime'>%d</span></nobr></td><td>%d</td><td>%d</td><td>%d</td><td>`, parser.BlockData.BlockId, parser.BlockData.BlockId, hash, parser.BlockData.Time, parser.BlockData.UserId, minerId, parser.BlockData.Level) data += utils.IntToStr(len(parser.TxMapArr)) data += "</td></tr>" } data += "</table>" } else if blockId > 0 { data += `<table class="table">` blockChain, err := c.OneRow("SELECT data, hash, cur_0l_miner_id, max_miner_id FROM block_chain WHERE id = ?", blockId).String() if err != nil { return "", utils.ErrInfo(err) } binToHexArray := []string{"sign", "public_key", "encrypted_message", "comment", "bin_public_keys"} hash := utils.BinToHex([]byte(blockChain["hash"])) binaryData := blockChain["data"] parser := new(dcparser.Parser) parser.DCDB = c.DCDB parser.BinaryData = []byte(binaryData) err = parser.ParseDataLite() if err != nil { return "", utils.ErrInfo(err) } parser.BlockData.Sign = utils.BinToHex(parser.BlockData.Sign) previous := parser.BlockData.BlockId - 1 next := parser.BlockData.BlockId + 1 levelsRange := utils.GetBlockGeneratorMinerIdRange(utils.StrToInt64(blockChain["cur_0l_miner_id"]), utils.StrToInt64(blockChain["max_miner_id"])) minerId, err := c.GetMinerId(parser.BlockData.UserId) if err != nil { return "", utils.ErrInfo(err) } _, _, _, CurrentUserId, _, _, _ := c.TestBlock() maxMinerId, err := c.Single("SELECT max(miner_id) FROM miners").Int64() if err != nil { return "", utils.ErrInfo(err) } currentMinerId, err := c.Single("SELECT miner_id FROM miners_data WHERE user_id = ?", CurrentUserId).Int64() if err != nil { return "", utils.ErrInfo(err) } NextBlockLevelsRange := utils.GetBlockGeneratorMinerIdRange(currentMinerId, maxMinerId) data += fmt.Sprintf(`<tr><td><strong>Raw data</strong></td><td><a href='ajax?controllerName=getBlock&id=%d&download=1' target='_blank'>Download</a></td></tr>`, parser.BlockData.BlockId) data += fmt.Sprintf(`<tr><td><strong>Block_id</strong></td><td>%d (<a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">Previous</a> / <a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">Next</a> )</td></tr>`, parser.BlockData.BlockId, previous, next) data += fmt.Sprintf(`<tr><td><strong>Hash</strong></td><td>%s</td></tr>`, hash) data += fmt.Sprintf(`<tr><td><strong>Time</strong></td><td><span class='unixtime'>%d</span> / %d</td></tr>`, parser.BlockData.Time, parser.BlockData.Time) data += fmt.Sprintf(`<tr><td><strong>User_id</strong></td><td>%d</td></tr>`, parser.BlockData.UserId) data += fmt.Sprintf(`<tr><td><strong>Miner_Id</strong></td><td>%d</td></tr>`, minerId) data += fmt.Sprintf(`<tr><td><strong>Level</strong></td><td>%d (%v) next: %v</td></tr>`, parser.BlockData.Level, levelsRange, NextBlockLevelsRange) data += fmt.Sprintf(`<tr><td><strong>Sign</strong></td><td>%s</td></tr>`, parser.BlockData.Sign) if len(parser.TxMapArr) > 0 { data += `<tr><td><strong>Transactions</strong></td><td><div><pre style='width: 700px'>` for i := 0; i < len(parser.TxMapArr); i++ { for k, data_ := range parser.TxMapArr[i] { if utils.InSliceString(k, binToHexArray) { parser.TxMapArr[i][k] = utils.BinToHex(data_) } if k == "file" { parser.TxMapArr[i][k] = []byte("file size: " + utils.IntToStr(len(data_))) } else if k == "code" { parser.TxMapArr[i][k] = utils.DSha256(data_) } else if k == "secret" { parser.TxMapArr[i][k] = utils.BinToHex(data_) } data += fmt.Sprintf("%v : %s\n", k, parser.TxMapArr[i][k]) } data += "\n\n" } data += "</pre></div></td></tr>" } data += "</table>" } // пока панель тут myNotice := make(map[string]string) if c.SessUserId > 0 { myNotice, err = c.GetMyNoticeData(c.SessUserId, c.SessUserId, c.MyPrefix, c.Lang) if err != nil { return "", utils.ErrInfo(err) } } TemplateStr, err := makeTemplate("block_explorer", "blockExplorer", &BlockExplorerPage{ Lang: c.Lang, CurrencyList: c.CurrencyListCf, MyNotice: myNotice, Data: data, Start: start, BlockId: blockId, PoolAdmin: c.PoolAdmin, SessRestricted: c.SessRestricted, UserId: c.SessUserId}) if err != nil { return "", utils.ErrInfo(err) } return TemplateStr, nil }