示例#1
0
文件: abuse.go 项目: dzyk/dcoin-go
func (c *Controller) Abuse() (string, error) {

	var err error

	txType := "Abuses"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	var countAbusesArr []int
	for i := 0; i < 20; i++ {
		countAbusesArr = append(countAbusesArr, i)
	}

	TemplateStr, err := makeTemplate("abuse", "abuse", &AbusePage{
		Alert:          c.Alert,
		Lang:           c.Lang,
		CountAbusesArr: countAbusesArr,
		ShowSignData:   c.ShowSignData,
		SignData:       "",
		UserId:         c.SessUserId,
		CountSignArr:   c.CountSignArr,
		TimeNow:        timeNow,
		TxType:         txType,
		TxTypeId:       txTypeId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#2
0
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
}
示例#3
0
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
}
示例#4
0
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
}
示例#5
0
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
}
示例#6
0
func CleanExit() {
	Clean()
	if utils.DB != nil && utils.DB.DB != nil {
		utils.DB.ExecSql(`INSERT INTO stop_daemons(stop_time) VALUES (?)`, utils.Time())
	} else {
		os.Exit(0)
	}
}
示例#7
0
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
}
示例#8
0
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
}
示例#9
0
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
}
示例#10
0
func (c *Controller) ChangeHost() (string, error) {

	txType := "ChangeHost"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	if !c.PoolAdmin || c.SessRestricted != 0 {
		return "", utils.ErrInfo(errors.New("access denied"))
	}

	data, err := c.OneRow("SELECT http_host, tcp_host, host_status FROM " + c.MyPrefix + "my_table").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	data2, err := c.OneRow("SELECT http_host, tcp_host, e_host FROM miners_data WHERE user_id = ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(data["http_host"]) == 0 {
		data["http_host"] = data2["http_host"]
	}
	if len(data["tcp_host"]) == 0 {
		data["tcp_host"] = data2["tcp_host"]
	}
	if len(data["e_host"]) == 0 {
		data["e_host"] = data2["e_host"]
	}
	if data["e_host"] == "" {
		data["e_host"] = "0"
	}

	statusArray := map[string]string{"my_pending": c.Lang["local_pending"], "approved": c.Lang["status_approved"]}
	data["host_status"] = statusArray[data["host_status"]]

	limitsText := strings.Replace(c.Lang["change_host_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_change_host"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_change_host_period"]], -1)

	TemplateStr, err := makeTemplate("change_host", "changeHost", &changeHostPage{
		Alert:        c.Alert,
		UserId:       c.SessUserId,
		CountSignArr: c.CountSignArr,
		Data:         data,
		TimeNow:      timeNow,
		TxType:       txType,
		TxTypeId:     txTypeId,
		LimitsText:   limitsText,
		ShowSignData: c.ShowSignData,
		Community:    c.Community,
		SignData:     "",
		Lang:         c.Lang})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#11
0
func (c *Controller) NewCfProject() (string, error) {

	var err error

	txType := "NewCfProject"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	cfCategory := utils.MakeCfCategories(c.Lang)

	latitude := "39.94887"
	longitude := "-75.15005"
	city := "Pennsylvania, USA"
	endTime := utils.Time() + 3600*24*7 + 3600

	var countDaysArr []int
	for i := 7; i < 90; i++ {
		countDaysArr = append(countDaysArr, i)
	}

	TemplateStr, err := makeTemplate("new_cf_project", "newCfProject", &NewCfProjectPage{
		Alert:        c.Alert,
		Lang:         c.Lang,
		CountSignArr: c.CountSignArr,
		ShowSignData: c.ShowSignData,
		UserId:       c.SessUserId,
		TimeNow:      timeNow,
		TxType:       txType,
		TxTypeId:     txTypeId,
		Latitude:     latitude,
		Longitude:    longitude,
		EndTime:      endTime,
		City:         city,
		CfCategory:   cfCategory,
		CountDaysArr: countDaysArr,
		CurrencyList: c.CurrencyList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#12
0
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
}
示例#13
0
func UnbanNodes(chBreaker chan bool, chAnswer chan string) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("daemon Recovered", r)
			panic(r)
		}
	}()

	GoroutineName := "UnbanNodes"
	d := new(daemon)
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}
	d.goRoutineName = GoroutineName
	d.chAnswer = chAnswer
	d.chBreaker = chBreaker
	d.sleepTime = 3600
	if !d.CheckInstall(chBreaker, chAnswer, GoroutineName) {
		return
	}
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}

BEGIN:
	for {
		log.Info(GoroutineName)
		MonitorDaemonCh <- []string{GoroutineName, utils.Int64ToStr(utils.Time())}

		// проверим, не нужно ли нам выйти из цикла
		if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) {
			break BEGIN
		}

		err = d.ExecSql("DELETE FROM nodes_ban")
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		if d.dSleep(d.sleepTime) {
			break BEGIN
		}
	}
	log.Debug("break BEGIN %v", GoroutineName)
}
示例#14
0
func (c *Controller) EDataBaseDump() (string, error) {

	if !c.NodeAdmin || c.SessRestricted != 0 {
		return "", utils.ErrInfo(errors.New("Permission denied"))
	}

	allTables, err := c.GetAllTables()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	c.r.ParseForm()

	mainMap := make(map[string][]map[string]string)

	for _, table := range allTables {
		re := regexp.MustCompile("^e_")
		match := re.FindStringSubmatch(table)
		if len(match) > 0 {
			data, err := c.GetAll(`SELECT * FROM `+table, -1)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			for k, arr := range data {
				for name, value := range arr {
					if ok, _ := regexp.MatchString("(tx_hash)", name); ok {
						data[k][name] = string(utils.BinToHex([]byte(value)))
					}
				}
			}
			mainMap[table] = data
		}
	}

	jsonData, _ := json.Marshal(mainMap)
	log.Debug(string(jsonData))

	c.w.Header().Set("Content-Type", "text/plain")
	c.w.Header().Set("Content-Length", utils.IntToStr(len(jsonData)))
	t := time.Unix(utils.Time(), 0)
	c.w.Header().Set("Content-Disposition", `attachment; filename="dcoin_e_backup-`+t.Format(c.TimeFormat)+`.txt`)
	if _, err := c.w.Write(jsonData); err != nil {
		return "", utils.ErrInfo(errors.New("unable to write text"))
	}

	return "", nil
}
示例#15
0
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
}
示例#16
0
func EPayment(paymentInfo string, currencyId, txTime int64, amount float64, paymentId int64, paymentSystem string, eCommission float64) error {

	var userId int64
	r, _ := regexp.Compile(`(?i)token\-([0-9]+)`)
	t_ := r.FindStringSubmatch(paymentInfo)
	token := ""
	if len(t_) > 0 {
		token = t_[1]
	} else {
		userId = utils.StrToInt64(paymentInfo)
	}
	var buyCurrencyId int64
	if len(token) > 0 {
		err := utils.DB.ExecSql(`UPDATE e_tokens SET status = 'paid' WHERE id = ?`, token)
		if err != nil {
			return utils.ErrInfo(err)
		}
		data, err := utils.DB.OneRow(`SELECT user_id, buy_currency_id FROM e_tokens WHERE id = ?`, token).Int64()
		if err != nil {
			return utils.ErrInfo(err)
		}
		userId = data["user_id"]

		buyCurrencyId = data["buy_currency_id"]
	}
	err := utils.DB.ExecSql(`INSERT INTO e_adding_funds_`+paymentSystem+` (id, user_id, currency_id, time, amount) VALUES (?, ?, ?, ?, ?)`, paymentId, userId, currencyId, txTime, amount)
	if err != nil {
		return utils.ErrInfo(err)
	}
	if userId > 0 {
		err = utils.UpdEWallet(userId, currencyId, utils.Time(), amount, false)
		if err != nil {
			return utils.ErrInfo(err)
		}

		// автоматом создаем ордер, если это запрос через кошель Dcoin
		if len(token) > 0 {
			err = NewForexOrder(userId, amount, 1, currencyId, buyCurrencyId, "buy", eCommission)
			if err != nil {
				return utils.ErrInfo(err)
			}
		}
	}
	return nil
}
示例#17
0
func main() {

	runtime.LockOSThread()

	var width uint = 800
	var height uint = 600
	var thrustWindow *window.Window
	if runtime.GOOS == "darwin" {
		height = 578
	}
	if utils.Desktop() && (winVer() >= 6 || winVer() == 0) {
		thrust.Start()
		thrustWindow = thrust.NewWindow(thrust.WindowOptions{
			RootUrl:  "http://localhost:8989/loader.html",
			HasFrame: true,
			Title:    "Dcoin",
			Size:     commands.SizeHW{Width: width, Height: height},
		})

		thrust.NewEventHandler("*", func(cr commands.CommandResponse) {
			//fmt.Println(fmt.Sprintf("======Event(%s %d) - Signaled by Command (%s)", cr.TargetID, cr.Type))
			if cr.TargetID > 1 && cr.Type == "closed" {
				if utils.DB != nil && utils.DB.DB != nil {
					utils.DB.ExecSql(`INSERT INTO stop_daemons(stop_time) VALUES (?)`, utils.Time())
				} else {
					thrust.Exit()
					os.Exit(0)
				}
			}
		})
		thrustWindow.Show()
		thrustWindow.Focus()
		go func() {
			http.HandleFunc("/static/img/main_loader.gif", main_loader)
			http.HandleFunc("/loader.html", main_loader_html)
			http.ListenAndServe(":8989", nil)
		}()
	}
	tray()

	go dcoin.Start("", thrustWindow)

	enterLoop()

}
示例#18
0
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

}
示例#19
0
func (c *Controller) ChangeGeolocation() (string, error) {

	var err error

	txType := "ChangeGeolocation"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	myGeolocationStr, err := c.Single(`SELECT geolocation FROM ` + c.MyPrefix + `my_table`).String()
	if len(myGeolocationStr) == 0 {
		myGeolocationStr = "39.94887, -75.15005"
	}
	x := strings.Split(myGeolocationStr, ", ")
	myGeolocation := make(map[string]string)
	myGeolocation["lat"] = x[0]
	myGeolocation["lon"] = x[1]

	myCountry, err := c.Single("SELECT country FROM miners_data WHERE user_id = ?", c.SessUserId).Int()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	limitsText := strings.Replace(c.Lang["geolocation_limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_change_geolocation"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_change_geolocation_period"]], -1)

	TemplateStr, err := makeTemplate("change_geolocation", "changeGeolocation", &changeGeolocationPage{
		Alert:         c.Alert,
		Lang:          c.Lang,
		TxTypeId:      txTypeId,
		TimeNow:       timeNow,
		UserId:        c.SessUserId,
		CountSignArr:  c.CountSignArr,
		ShowSignData:  c.ShowSignData,
		SignData:      "",
		LimitsText:    limitsText,
		MyCountry:     myCountry,
		Countries:     consts.Countries,
		MyGeolocation: myGeolocation})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#20
0
func (c *Controller) RestoringAccess() (string, error) {

	var err error

	txType := "ChangeKeyActive"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	adminUserId, err := c.GetAdminUserId()

	data, err := c.OneRow("SELECT change_key, change_key_time, change_key_close FROM users WHERE user_id  =  ?", c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// разрешил ли уже юзер менять свой ключ админу
	changeKeyStatus := data["change_key"]

	requests := ""
	if len(data["change_key_status"]) > 0 && len(data["change_key_close"]) > 0 {
		t := time.Unix(utils.StrToInt64(data["change_key_time"]), 0)
		requests = t.Format(c.TimeFormat)
	}

	TemplateStr, err := makeTemplate("restoring_access", "restoringAccess", &restoringAccessPage{
		Alert:           c.Alert,
		Lang:            c.Lang,
		ShowSignData:    c.ShowSignData,
		SignData:        "",
		UserId:          c.SessUserId,
		CountSignArr:    c.CountSignArr,
		TimeNow:         timeNow,
		TxType:          txType,
		TxTypeId:        txTypeId,
		AdminUserId:     adminUserId,
		ChangeKeyStatus: changeKeyStatus,
		Requests:        requests})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#21
0
func (c *Controller) NewHolidays() (string, error) {

	var err error

	txType := "NewHolidays"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	TemplateStr, err := makeTemplate("new_holidays", "newHolidays", &newHolidaysPage{
		Alert:        c.Alert,
		Lang:         c.Lang,
		TxTypeId:     txTypeId,
		TimeNow:      timeNow,
		CountSignArr: c.CountSignArr,
		ShowSignData: c.ShowSignData,
		SignData:     ""})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#22
0
func (c *Controller) ChangeKeyRequest() (string, error) {

	txType := "ChangeKeyActive"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	TemplateStr, err := makeTemplate("change_key_request", "changeKeyRequest", &changeKeyRequestPage{
		Alert:        c.Alert,
		Lang:         c.Lang,
		ShowSignData: c.ShowSignData,
		SignData:     "",
		UserId:       c.SessUserId,
		CountSignArr: c.CountSignArr,
		TimeNow:      timeNow,
		TxType:       txType,
		TxTypeId:     txTypeId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#23
0
文件: dcoin.go 项目: dzyk/dcoin-go
func Stop() {
	log.Debug("Stop()")
	IosLog("Stop()")
	var err error
	utils.DB, err = utils.NewDbConnect(configIni)
	log.Debug("DCOIN Stop : %v", utils.DB)
	IosLog("utils.DB:" + fmt.Sprintf("%v", utils.DB))
	if err != nil {
		IosLog("err:" + fmt.Sprintf("%s", utils.ErrInfo(err)))
		log.Error("%v", utils.ErrInfo(err))
		//panic(err)
		//os.Exit(1)
	}
	err = utils.DB.ExecSql(`INSERT INTO stop_daemons(stop_time) VALUES (?)`, utils.Time())
	if err != nil {
		IosLog("err:" + fmt.Sprintf("%s", utils.ErrInfo(err)))
		log.Error("%v", utils.ErrInfo(err))
	}
	log.Debug("DCOIN Stop")
	IosLog("DCOIN Stop")
}
示例#24
0
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
}
示例#25
0
文件: windows.go 项目: dzyk/dcoin-go
func KillPid(pid string) error {
	if utils.DB != nil && utils.DB.DB != nil {
		err := utils.DB.ExecSql(`INSERT INTO stop_daemons(stop_time) VALUES (?)`, utils.Time())
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
			return err
		}
	}
	//var rez []byte
	/*file, err := os.OpenFile("kill", os.O_APPEND|os.O_WRONLY|os.O_CREATE,0600)
	if err != nil {
		return err
	}
	defer file.Close()
	file.WriteString("1")
	*/
	/*err := exec.Command("taskkill","/pid", pid).Start()
	if err!=nil {
		return err
	}*/
	rez, err := exec.Command("tasklist", "/fi", "PID eq "+pid).Output()
	if err != nil {
		return err
	}
	if string(rez) == "" {
		return fmt.Errorf("null")
	} else {
		log.Debug("%rez s", string(rez))
		fmt.Println("rez", string(rez))
		if ok, _ := regexp.MatchString(`(?i)PID`, string(rez)); !ok {
			return fmt.Errorf("null")
		} else {
			return nil
		}
	}
	//fmt.Printf("taskkill /pid %s: %s\n", pid, rez)
	return nil
}
示例#26
0
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
}
示例#27
0
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
}
示例#28
0
func (c *Controller) AdminVariables() (string, error) {

	txType := "AdminVariables"
	txTypeId := utils.TypeInt(txType)
	timeNow := utils.Time()

	variables, err := c.GetMap(`SELECT * FROM variables`, "name", "value")

	TemplateStr, err := makeTemplate("admin_variables", "adminVariables", &adminVariablesPage{
		Variables:    variables,
		Alert:        c.Alert,
		Lang:         c.Lang,
		ShowSignData: c.ShowSignData,
		SignData:     "",
		UserId:       c.SessUserId,
		CountSignArr: c.CountSignArr,
		TimeNow:      timeNow,
		TxType:       txType,
		TxTypeId:     txTypeId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
示例#29
0
/**
Обработка данных (блоков или транзакций), пришедших с гейта. Только проверка.
*/
func (p *Parser) ParseDataGate(onlyTx bool) error {

	var err error
	p.dataPre()
	p.TxIds = []string{}

	p.Variables, err = p.GetAllVariables()
	if err != nil {
		return utils.ErrInfo(err)
	}

	transactionBinaryData := p.BinaryData
	var transactionBinaryDataFull []byte

	// если это транзакции (type>0), а не блок (type==0)
	if p.dataType > 0 {

		// проверим, есть ли такой тип тр-ий
		if len(consts.TxTypes[p.dataType]) == 0 {
			return p.ErrInfo("Incorrect tx type " + utils.IntToStr(p.dataType))
		}

		log.Debug("p.dataType %v", p.dataType)
		transactionBinaryData = append(utils.DecToBin(int64(p.dataType), 1), transactionBinaryData...)
		transactionBinaryDataFull = transactionBinaryData

		// нет ли хэша этой тр-ии у нас в БД?
		err = p.CheckLogTx(transactionBinaryDataFull)
		if err != nil {
			return p.ErrInfo(err)
		}

		p.TxHash = utils.Md5(transactionBinaryData)

		// преобразуем бинарные данные транзакции в массив
		p.TxSlice, err = p.ParseTransaction(&transactionBinaryData)
		if err != nil {
			return p.ErrInfo(err)
		}
		log.Debug("p.TxSlice", p.TxSlice)
		if len(p.TxSlice) < 3 {
			return p.ErrInfo(errors.New("len(p.TxSlice) < 3"))
		}

		// время транзакции может быть немного больше, чем время на ноде.
		// у нода может быть просто не настроено время.
		// время транзакции используется только для борьбы с атаками вчерашними транзакциями.
		// А т.к. мы храним хэши в log_transaction за 36 часов, то боятся нечего.
		curTime := utils.Time()
		if utils.BytesToInt64(p.TxSlice[2])-consts.MAX_TX_FORW > curTime || utils.BytesToInt64(p.TxSlice[2]) < curTime-consts.MAX_TX_BACK {
			return p.ErrInfo(errors.New("incorrect tx time"))
		}
		// $this->transaction_array[3] могут подсунуть пустой
		if !utils.CheckInputData(p.TxSlice[3], "bigint") {
			return p.ErrInfo(errors.New("incorrect user id"))
		}
	}

	// если это блок
	if p.dataType == 0 {

		txCounter := make(map[int64]int64)

		// если есть $only_tx=true, то значит идет восстановление уже проверенного блока и заголовок не требуется
		if !onlyTx {
			err = p.ParseBlock()
			if err != nil {
				return p.ErrInfo(err)
			}

			// проверим данные, указанные в заголовке блока
			err = p.CheckBlockHeader()
			if err != nil {
				return p.ErrInfo(err)
			}
		}
		log.Debug("onlyTx", onlyTx)

		// если в ходе проверки тр-ий возникает ошибка, то вызываем откатчик всех занесенных тр-ий. Эта переменная для него
		p.fullTxBinaryData = p.BinaryData
		var txForRollbackTo []byte
		if len(p.BinaryData) > 0 {
			for {
				transactionSize := utils.DecodeLength(&p.BinaryData)
				if len(p.BinaryData) == 0 {
					return utils.ErrInfo(fmt.Errorf("empty BinaryData"))
				}

				// отчекрыжим одну транзакцию от списка транзакций
				transactionBinaryData := utils.BytesShift(&p.BinaryData, transactionSize)
				transactionBinaryDataFull = transactionBinaryData

				// добавляем взятую тр-ию в набор тр-ий для RollbackTo, в котором пойдем в обратном порядке
				txForRollbackTo = append(txForRollbackTo, utils.EncodeLengthPlusData(transactionBinaryData)...)

				// нет ли хэша этой тр-ии у нас в БД?
				err = p.CheckLogTx(transactionBinaryDataFull)
				if err != nil {
					p.RollbackTo(txForRollbackTo, true, false)
					return p.ErrInfo(err)
				}

				p.TxHash = utils.Md5(transactionBinaryData)
				p.TxSlice, err = p.ParseTransaction(&transactionBinaryData)
				log.Debug("p.TxSlice %s", p.TxSlice)
				if err != nil {
					p.RollbackTo(txForRollbackTo, true, false)
					return p.ErrInfo(err)
				}

				var userId int64
				// txSlice[3] могут подсунуть пустой
				if len(p.TxSlice) > 3 {
					if !utils.CheckInputData(p.TxSlice[3], "int64") {
						return utils.ErrInfo(fmt.Errorf("empty user_id"))
					} else {
						userId = utils.BytesToInt64(p.TxSlice[3])
					}
				} else {
					return utils.ErrInfo(fmt.Errorf("empty user_id"))
				}

				// считаем по каждому юзеру, сколько в блоке от него транзакций
				txCounter[userId]++

				// чтобы 1 юзер не смог прислать дос-блок размером в 10гб, который заполнит своими же транзакциями
				if txCounter[userId] > p.Variables.Int64["max_block_user_transactions"] {
					p.RollbackTo(txForRollbackTo, true, false)
					return utils.ErrInfo(fmt.Errorf("max_block_user_transactions"))
				}

				// проверим, есть ли такой тип тр-ий
				_, ok := consts.TxTypes[utils.BytesToInt(p.TxSlice[1])]
				if !ok {
					return utils.ErrInfo(fmt.Errorf("nonexistent type"))
				}

				p.TxMap = map[string][]byte{}

				// для статы
				p.TxIds = append(p.TxIds, string(p.TxSlice[1]))

				MethodName := consts.TxTypes[utils.BytesToInt(p.TxSlice[1])]
				log.Debug("MethodName", MethodName+"Init")
				err_ := utils.CallMethod(p, MethodName+"Init")
				if _, ok := err_.(error); ok {
					log.Debug("error: %v", err)
					p.RollbackTo(txForRollbackTo, true, true)
					return utils.ErrInfo(err_.(error))
				}

				log.Debug("MethodName", MethodName+"Front")
				err_ = utils.CallMethod(p, MethodName+"Front")
				if _, ok := err_.(error); ok {
					log.Debug("error: %v", err)
					p.RollbackTo(txForRollbackTo, true, true)
					return utils.ErrInfo(err_.(error))
				}

				// пишем хэш тр-ии в лог
				err = p.InsertInLogTx(transactionBinaryDataFull, utils.BytesToInt64(p.TxMap["time"]))
				if err != nil {
					return utils.ErrInfo(err)
				}

				if len(p.BinaryData) == 0 {
					break
				}
			}
		}
	} else {

		// Оперативные транзакции
		MethodName := consts.TxTypes[p.dataType]
		log.Debug("MethodName", MethodName+"Init")
		err_ := utils.CallMethod(p, MethodName+"Init")
		if _, ok := err_.(error); ok {
			return utils.ErrInfo(err_.(error))
		}

		log.Debug("MethodName", MethodName+"Front")
		err_ = utils.CallMethod(p, MethodName+"Front")
		if _, ok := err_.(error); ok {
			return utils.ErrInfo(err_.(error))
		}

		// пишем хэш тр-ии в лог
		err = p.InsertInLogTx(transactionBinaryDataFull, utils.BytesToInt64(p.TxMap["time"]))
		if err != nil {
			return utils.ErrInfo(err)
		}
	}

	return nil
}
func MaxOtherCurrenciesGenerator(chBreaker chan bool, chAnswer chan string) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("daemon Recovered", r)
			panic(r)
		}
	}()

	const GoroutineName = "MaxOtherCurrenciesGenerator"
	d := new(daemon)
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}
	d.goRoutineName = GoroutineName
	d.chAnswer = chAnswer
	d.chBreaker = chBreaker
	if utils.Mobile() {
		d.sleepTime = 3600
	} else {
		d.sleepTime = 60
	}
	if !d.CheckInstall(chBreaker, chAnswer, GoroutineName) {
		return
	}
	d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
	if d.DCDB == nil {
		return
	}

	err = d.notMinerSetSleepTime(1800)
	if err != nil {
		log.Error("%v", err)
		return
	}

BEGIN:
	for {
		log.Info(GoroutineName)
		MonitorDaemonCh <- []string{GoroutineName, utils.Int64ToStr(utils.Time())}

		// проверим, не нужно ли нам выйти из цикла
		if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) {
			break BEGIN
		}

		err, restart := d.dbLock()
		if restart {
			break BEGIN
		}
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		blockId, err := d.GetBlockId()
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		if blockId == 0 {
			if d.unlockPrintSleep(utils.ErrInfo("blockId == 0"), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		_, _, myMinerId, _, _, _, err := d.TestBlock()
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		// а майнер ли я ?
		if myMinerId == 0 {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		variables, err := d.GetAllVariables()
		curTime := utils.Time()

		totalCountCurrencies, err := d.GetCountCurrencies()
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		// проверим, прошло ли 2 недели с момента последнего обновления
		pctTime, err := d.Single("SELECT max(time) FROM max_other_currencies_time").Int64()
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		if curTime-pctTime <= variables.Int64["new_max_other_currencies"] {
			if d.unlockPrintSleep(utils.ErrInfo("14 day error"), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		// берем все голоса
		maxOtherCurrenciesVotes := make(map[int64][]map[int64]int64)
		rows, err := d.Query("SELECT currency_id, count, count(user_id) as votes FROM votes_max_other_currencies GROUP BY currency_id, count ORDER BY currency_id, count ASC")
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		for rows.Next() {
			var currency_id, count, votes int64
			err = rows.Scan(&currency_id, &count, &votes)
			if err != nil {
				rows.Close()
				if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			maxOtherCurrenciesVotes[currency_id] = append(maxOtherCurrenciesVotes[currency_id], map[int64]int64{count: votes})
		}
		rows.Close()

		newMaxOtherCurrenciesVotes := make(map[string]int64)
		for currencyId, countAndVotes := range maxOtherCurrenciesVotes {
			newMaxOtherCurrenciesVotes[utils.Int64ToStr(currencyId)] = utils.GetMaxVote(countAndVotes, 0, totalCountCurrencies, 10)
		}

		jsonData, err := json.Marshal(newMaxOtherCurrenciesVotes)

		_, myUserId, _, _, _, _, err := d.TestBlock()
		forSign := fmt.Sprintf("%v,%v,%v,%s", utils.TypeInt("NewMaxOtherCurrencies"), curTime, myUserId, jsonData)
		log.Debug("forSign = %v", forSign)
		binSign, err := d.GetBinSign(forSign, myUserId)
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}
		data := utils.DecToBin(utils.TypeInt("NewMaxOtherCurrencies"), 1)
		data = append(data, utils.DecToBin(curTime, 4)...)
		data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(myUserId))...)
		data = append(data, utils.EncodeLengthPlusData(jsonData)...)
		data = append(data, utils.EncodeLengthPlusData([]byte(binSign))...)

		err = d.InsertReplaceTxInQueue(data)
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		p := new(dcparser.Parser)
		p.DCDB = d.DCDB
		err = p.TxParser(utils.HexToBin(utils.Md5(data)), data, true)
		if err != nil {
			if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		d.dbUnlock()

		if d.dSleep(d.sleepTime) {
			break BEGIN
		}
	}
	log.Debug("break BEGIN %v", GoroutineName)
}