Exemple #1
0
func (c *Controller) Information() (string, error) {

	var err error

	alertMessages_, err := c.GetAll(`SELECT * FROM alert_messages ORDER BY id DESC`, -1)
	var alertMessages []map[string]string
	for _, v := range alertMessages_ {
		show := false
		if v["currency_list"] != "ALL" {
			// проверим, есть ли у нас обещнные суммы с такой валютой
			amounts, err := c.Single("SELECT id FROM promised_amount WHERE currency_id IN (" + v["currency_list"] + ")").Int64()
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			if amounts > 0 {
				show = true
			}
		} else {
			show = true
		}
		if show {
			alertMessages = append(alertMessages, map[string]string{"id": v["id"], "message": v["message"]})
		}
	}

	TemplateStr, err := makeTemplate("information", "information", &InformationPage{
		Lang:          c.Lang,
		AlertMessages: alertMessages})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #2
0
func (c *Controller) Upgrade5() (string, error) {

	log.Debug("Upgrade5")

	geolocationLat := ""
	geolocationLon := ""
	geolocation, err := c.Single("SELECT geolocation FROM " + c.MyPrefix + "my_table").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(geolocation) > 0 {
		x := strings.Split(geolocation, ", ")
		if len(x) == 2 {
			geolocationLat = x[0]
			geolocationLon = x[1]
		}
	}

	saveAndGotoStep := strings.Replace(c.Lang["save_and_goto_step"], "[num]", "7", -1)
	upgradeMenu := utils.MakeUpgradeMenu(5)

	TemplateStr, err := makeTemplate("upgrade_5", "upgrade5", &upgrade5Page{
		Alert:           c.Alert,
		Lang:            c.Lang,
		SaveAndGotoStep: saveAndGotoStep,
		UpgradeMenu:     upgradeMenu,
		GeolocationLat:  geolocationLat,
		GeolocationLon:  geolocationLon,
		UserId:          c.SessUserId,
		Mobile:          utils.Mobile()})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #3
0
func (c *Controller) SaveNotifications() (string, error) {

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

	c.r.ParseForm()

	var data []map[string]interface{}
	err := json.Unmarshal([]byte(c.r.PostFormValue("data")), &data)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	log.Debug("data:", data)

	for k, _ := range data {
		err := c.ExecSql(`
				UPDATE `+c.MyPrefix+`my_notifications
				SET  email = ?,
					 sms =  ?,
					 mobile = ?
				WHERE name = ?
				`, data[k]["email"].(float64), data[k]["sms"].(float64), data[k]["mobile"].(float64), data[k]["name"].(string))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}

	return `{"error":0}`, nil

}
Exemple #4
0
func (a *AvailablekeyStruct) checkAvailableKey(key string) (int64, string, error) {
	publicKeyAsn, err := utils.GetPublicFromPrivate(key)
	if err != nil {
		log.Debug("%v", err)
		return 0, "", utils.ErrInfo(err)
	}
	log.Debug("publicKeyAsn: %s", publicKeyAsn)
	userId, err := a.Single("SELECT user_id FROM users WHERE hex(public_key_0) = ?", publicKeyAsn).Int64()
	if err != nil {
		return 0, "", utils.ErrInfo(err)
	}
	log.Debug("userId: %s", userId)
	if userId == 0 {
		return 0, "", errors.New("null userId")
	}
	allTables, err := a.GetAllTables()
	if err != nil {
		return 0, "", utils.ErrInfo(err)
	}
	// может другой юзер уже начал смену ключа. актуально для пула
	if utils.InSliceString(utils.Int64ToStr(userId)+"_my_table", allTables) {
		return 0, "", errors.New("exists _my_table")
	}
	return userId, string(publicKeyAsn), nil
}
Exemple #5
0
func Signals() {
	SigChan = make(chan os.Signal, 1)
	waitSig()
	var Term os.Signal = syscall.SIGTERM
	go func() {
		signal.Notify(SigChan, os.Interrupt, os.Kill, Term)
		<-SigChan
		fmt.Println("KILL SIGNAL")
		for _, ch := range utils.DaemonsChans {
			fmt.Println("ch.ChBreaker<-true")
			ch.ChBreaker <- true
		}
		for _, ch := range utils.DaemonsChans {
			fmt.Println(<-ch.ChAnswer)
		}
		log.Debug("Daemons killed")
		fmt.Println("Daemons killed")
		if utils.DB != nil && utils.DB.DB != nil {
			err := utils.DB.Close()
			fmt.Println("DB Closed")
			if err != nil {
				log.Error("%v", utils.ErrInfo(err))
				//panic(err)
			}
		}
		err := os.Remove(*utils.Dir + "/dcoin.pid")
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
			panic(err)
		}
		fmt.Println("removed " + *utils.Dir + "/dcoin.pid")
		os.Exit(1)
	}()
}
Exemple #6
0
func (c *Controller) SaveUserCoords() (string, error) {

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

	c.r.ParseForm()
	coordsJson := c.r.FormValue("coords_json")
	var coords [][2]int
	err := json.Unmarshal([]byte(coordsJson), &coords)
	if err != nil {
		return "", err
	}
	coordsType := c.r.FormValue("type")
	if coordsType != "face" && coordsType != "profile" {
		return "", errors.New("Incorrect type")
	}
	coordsJson_, err := json.Marshal(coords)
	if err != nil {
		return "", err
	}
	err = c.ExecSql("UPDATE "+c.MyPrefix+"my_table SET "+coordsType+"_coords = ?", string(coordsJson_))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return `{"success":"ok"}`, nil
}
Exemple #7
0
func (c *Controller) SaveHost() (string, error) {

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

	c.r.ParseForm()
	http_host := c.r.FormValue("http_host")
	if len(http_host) > 0 && http_host[len(http_host)-1:] != "/" {
		http_host += "/"
	}
	tcp_host := c.r.FormValue("tcp_host")

	if !utils.CheckInputData(http_host, "http_host") {
		return `{"error":"1"}`, nil
	}
	if !utils.CheckInputData(tcp_host, "tcp_host") {
		return `{"error":"1"}`, nil
	}

	err := c.ExecSql("UPDATE "+c.MyPrefix+"my_table SET http_host = ?, tcp_host = ?", http_host, tcp_host)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	return `{"error":"0"}`, nil
}
Exemple #8
0
func (c *Controller) EData() (string, error) {

	c.w.Header().Set("Access-Control-Allow-Origin", "*")

	// сколько всего продается DC
	eOrders, err := c.GetAll(`SELECT sell_currency_id, sum(amount) as amount FROM e_orders  WHERE sell_currency_id < 1000 AND empty_time = 0 GROUP BY sell_currency_id`, 100)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	values := ""
	for _, data := range eOrders {
		values += utils.ClearNull(data["amount"], 0) + ` d` + c.CurrencyList[utils.StrToInt64(data["sell_currency_id"])] + `, `
	}
	if len(values) > 0 {
		values = values[:len(values)-2]
	}
	ps, err := c.Single(`SELECT value FROM e_config WHERE name = 'ps'`).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	jsonData, err := json.Marshal(map[string]string{"values": values, "ps": ps})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return string(jsonData), nil

}
Exemple #9
0
func (c *Controller) CheckCfCurrency() (string, error) {

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

	c.r.ParseForm()
	projectCurrencyName := c.r.FormValue("project_currency_name")
	if !utils.CheckInputData(projectCurrencyName, "cf_currency_name") {
		return "", errors.New("incorrect project_currency_name")
	}

	// проверим, не занято ли имя валюты
	currency, err := c.Single("SELECT id FROM cf_projects WHERE project_currency_name = ? AND close_block_id = 0 AND del_block_id = 0", projectCurrencyName).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if currency > 0 {
		return `{"error":"` + c.Lang["currency_name_busy"] + `"}`, nil
	}

	// проверим, не занято ли имя валюты
	currency, err = c.Single("SELECT id FROM cf_currency WHERE name = ?", projectCurrencyName).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if currency > 0 {
		return `{"error":"` + c.Lang["currency_name_busy"] + `"}`, nil
	}

	return `{"success":"` + c.Lang["name_is_not_occupied"] + `"}`, nil
}
Exemple #10
0
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
}
Exemple #11
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
}
Exemple #12
0
func (t *TcpServer) Type7() {
	/* Выдаем тело указанного блока
	 * запрос шлет демон blocksCollection и queue_parser_blocks через p.GetBlocks()
	 */
	buf := make([]byte, 4)
	_, err := t.Conn.Read(buf)
	if err != nil {
		log.Error("%v", utils.ErrInfo(err))
		return
	}
	blockId := utils.BinToDec(buf)
	block, err := t.Single("SELECT data FROM block_chain WHERE id  =  ?", blockId).Bytes()
	if err != nil {
		log.Error("%v", utils.ErrInfo(err))
		return
	}

	log.Debug("blockId %x", blockId)
	log.Debug("block %x", block)
	err = utils.WriteSizeAndData(block, t.Conn)
	if err != nil {
		log.Error("%v", utils.ErrInfo(err))
		return
	}
}
Exemple #13
0
func (c *Controller) SaveEmailSms() (string, error) {

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

	c.r.ParseForm()

	err := c.ExecSql(`
			UPDATE `+c.MyPrefix+`my_table
			SET  email = ?,
					smtp_server =  ?,
					use_smtp =  ?,
					smtp_port =  ?,
					smtp_ssl =  ?,
					smtp_auth =  ?,
					smtp_username = ?,
					smtp_password = ?,
					sms_http_get_request = ?
			`, c.r.FormValue("email"), c.r.FormValue("smtp_server"), c.r.FormValue("use_smtp"), c.r.FormValue("smtp_port"), c.r.FormValue("smtp_ssl"), c.r.FormValue("smtp_auth"), c.r.FormValue("smtp_username"), c.r.FormValue("smtp_password"), c.r.FormValue("sms_http_get_request"))
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	return "", nil

}
Exemple #14
0
func (c *Controller) Chat() (string, error) {

	myChatName := utils.Int64ToStr(c.SessUserId)
	// возможно у отпарвителя есть ник
	name, err := c.Single(`SELECT name FROM users WHERE user_id = ?`, c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(name) > 0 {
		myChatName = name
	}

	TemplateStr, err := makeTemplate("chat", "chat", &chatPage{
		Community:    c.Community,
		CountSignArr: c.CountSignArr,
		CountSign:    c.CountSign,
		Lang:         c.Lang,
		ShowSignData: c.ShowSignData,
		SignData:     "",
		MyChatName:   myChatName,
		UserId:       c.SessUserId,
		IOS:          utils.IOS(),
		Mobile:       utils.Mobile()})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #15
0
func (c *Controller) EPages() (string, error) {

	var err error

	var title, text string
	if len(c.Parameters["page"]) > 0 {
		if !utils.CheckInputData(c.Parameters["page"], "string") {
			return "", utils.ErrInfo(err)
		}
		data, err := c.OneRow(`SELECT title, text from e_pages WHERE name = ? AND lang = ?`, c.Parameters["page"], c.LangInt).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		title = data["title"]
		text = data["text"]
	}

	TemplateStr, err := makeTemplate("e_pages", "ePages", &ePages{
		Lang:  c.Lang,
		Title: title,
		Text:  text})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #16
0
func (c *Controller) EncryptChatMessage() (string, error) {

	var err error

	c.r.ParseForm()

	receiver := c.r.FormValue("receiver")
	message := c.r.FormValue("message")
	if len(message) > 5120 {
		return "", errors.New("incorrect message")
	}

	publicKey, err := c.Single("SELECT public_key_0 FROM users WHERE user_id  =  ?", receiver).Bytes()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	if len(publicKey) > 0 {
		pub, err := utils.BinToRsaPubKey(publicKey)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		enc_, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(message))
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		return utils.JsonAnswer(string(utils.BinToHex(enc_)), "success").String(), nil
	} else {
		return utils.JsonAnswer("Incorrect user_id", "error").String(), nil
	}

}
Exemple #17
0
func (c *Controller) ELogin() (string, error) {

	c.r.ParseForm()
	email := c.r.FormValue("email")
	password := c.r.FormValue("password")
	if len(password) > 50 || len(password) < 1 {
		return "", errors.New(c.Lang["invalid_pass"])
	}

	data, err := c.OneRow("SELECT id, salt FROM e_users WHERE email = ?", email).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(data) == 0 {
		return "", errors.New(c.Lang["email_is_not_registered"])
	}

	// проверяем, верный ли пароль
	passAndSalt := utils.Sha256(password + data["salt"])
	userId, err := utils.DB.Single("SELECT id FROM e_users WHERE id  =  ? AND password  =  ?", data["id"], passAndSalt).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if userId == 0 {
		return "", errors.New(c.Lang["wrong_pass"])
	}

	c.sess.Set("e_user_id", userId)

	return utils.JsonAnswer("success", "success").String(), nil
}
Exemple #18
0
func (c *Controller) ERedirect() (string, error) {

	c.r.ParseForm()
	token := c.r.FormValue("FormToken")
	amount := c.r.FormValue("FormExAmount")
	buyCurrencyId := utils.StrToInt64(c.r.FormValue("FormDC"))

	if !utils.CheckInputData(token, "string") {
		return "", errors.New("incorrect data")
	}

	// order_id занесем когда поуступят деньги в платежной системе
	err := c.ExecSql(`UPDATE e_tokens SET buy_currency_id = ?, amount_fiat = ? WHERE token = ?`, buyCurrencyId, utils.StrToFloat64(c.r.FormValue("FormExAmount")), token)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	tokenId, err := c.Single(`SELECT id FROM e_tokens WHERE token = ?`, token).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	TemplateStr, err := makeTemplate("e_redirect", "eRedirect", &ERedirectPage{
		Lang:    c.Lang,
		EConfig: c.EConfig,
		TokenId: tokenId,
		EURL:    c.EURL,
		MDesc:   base64.StdEncoding.EncodeToString([]byte("token-" + tokenId)),
		Amount:  amount})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #19
0
func (c *Controller) EMyHistory() (string, error) {

	var err error

	if c.SessUserId == 0 {
		return `<script language="javascript"> window.location.href = "` + c.EURL + `"</script>If you are not redirected automatically, follow the <a href="` + c.EURL + `">` + c.EURL + `</a>`, nil
	}

	currencyList, err := utils.EGetCurrencyList()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	//fmt.Println("currencyList", currencyList)
	var myHistory []*EmyHistory

	rows, err := c.Query(c.FormatQuery(`
			SELECT id, time, amount, sell_rate, sell_currency_id, buy_currency_id
			FROM e_trade
			WHERE user_id = ?
			ORDER BY time DESC
			LIMIT 40
			`), c.SessUserId)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	for rows.Next() {
		myHist := new(EmyHistory)
		err = rows.Scan(&myHist.Id, &myHist.Time, &myHist.Amount, &myHist.SellRate, &myHist.SellCurrencyId, &myHist.BuyCurrencyId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// определим тип ордера и пару
		if myHist.SellCurrencyId < 1000 {
			myHist.OrderType = "sell"
			myHist.SellRate = 1 / myHist.SellRate
			myHist.Total = myHist.Amount * myHist.SellRate
			myHist.Amount = myHist.Amount
			myHist.Pair = currencyList[myHist.SellCurrencyId] + "/" + currencyList[myHist.BuyCurrencyId]
		} else {
			myHist.OrderType = "buy"
			myHist.Total = myHist.Amount
			myHist.Amount = myHist.Amount * (1 / myHist.SellRate)
			myHist.Pair = currencyList[myHist.BuyCurrencyId] + "/" + currencyList[myHist.SellCurrencyId]
		}

		myHistory = append(myHistory, myHist)
	}

	TemplateStr, err := makeTemplate("e_my_history", "eMyHistory", &eMyHistoryPage{
		Lang:         c.Lang,
		UserId:       c.SessUserId,
		MyHistory:    myHistory,
		CurrencyList: currencyList})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #20
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
}
Exemple #21
0
func (c *Controller) ESignUp() (string, error) {

	c.r.ParseForm()
	email := c.r.FormValue("email")
	password := c.r.FormValue("password")
	if len(password) > 50 || len(password) < 1 {
		return "", errors.New(c.Lang["invalid_pass"])
	}

	existsEmail, err := c.Single("SELECT id FROM e_users WHERE email = ?", email).Int64()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if existsEmail > 0 {
		return "", errors.New(c.Lang["exists_email"])
	}

	salt := utils.RandSeq(32)
	passAndSalt := utils.DSha256(password + salt)
	userId, err := c.ExecSqlGetLastInsertId("INSERT INTO e_users ( email, password, ip, salt ) VALUES ( ?, ?, ?, ? )", "id", email, passAndSalt, c.r.RemoteAddr, salt)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	c.sess.Set("e_user_id", userId)

	return utils.JsonAnswer("success", "success").String(), nil
}
Exemple #22
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
}
Exemple #23
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
}
Exemple #24
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
}
Exemple #25
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
}
Exemple #26
0
func (c *Controller) Upgrade4() (string, error) {

	log.Debug("Upgrade4")

	videoUrl := ""

	// есть ли загруженное видео.
	data, err := c.OneRow("SELECT video_url_id, video_type FROM " + c.MyPrefix + "my_table").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	switch data["video_type"] {
	case "youtube":
		videoUrl = "http://www.youtube.com/embed/" + data["video_url_id"]
	case "vimeo":
		videoUrl = "http://www.vimeo.com/embed/" + data["video_url_id"]
	case "youku":
		videoUrl = "http://www.youku.com/embed/" + data["video_url_id"]
	}

	saveAndGotoStep := strings.Replace(c.Lang["save_and_goto_step"], "[num]", "6", -1)
	upgradeMenu := utils.MakeUpgradeMenu(4)

	var userVideoMp4 string
	path := *utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.mp4"
	if _, err := os.Stat(path); err == nil {
		userVideoMp4 = "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.mp4"
	}
	var userVideoWebm string
	path = *utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.webm"
	if _, err := os.Stat(path); err == nil {
		userVideoWebm = "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.webm"
	}
	var userVideoOgg string
	path = *utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.ogg"
	if _, err := os.Stat(path); err == nil {
		userVideoOgg = "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.ogg"
	}

	TemplateStr, err := makeTemplate("upgrade_4", "upgrade4", &upgrade4Page{
		Alert:           c.Alert,
		Lang:            c.Lang,
		SaveAndGotoStep: saveAndGotoStep,
		UpgradeMenu:     upgradeMenu,
		VideoUrl:        videoUrl,
		UserVideoMp4:    userVideoMp4,
		UserVideoWebm:   userVideoWebm,
		UserVideoOgg:    userVideoOgg,
		Mobile:          utils.Mobile(),
		UserId:          c.SessUserId})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemple #27
0
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
}
Exemple #28
0
func (c *Controller) RestartDb() (string, error) {

	if ok, _ := regexp.MatchString(`(\:\:)|(127\.0\.0\.1)`, c.r.RemoteAddr); ok {
		err := daemons.ClearDb(nil, "")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	} else {
		return "", utils.ErrInfo("Access denied for " + c.r.RemoteAddr)
	}
	return "", nil
}
func (c *Controller) RewritePrimaryKeySave() (string, error) {

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

	if len(c.r.FormValue("n")) > 0 {

		c.r.ParseForm()
		n := []byte(c.r.FormValue("n"))
		e := []byte(c.r.FormValue("e"))
		if !utils.CheckInputData(n, "hex") {
			return "", utils.ErrInfo(errors.New("incorrect n"))
		}
		if !utils.CheckInputData(e, "hex") {
			return "", utils.ErrInfo(errors.New("incorrect e"))
		}
		publicKey := utils.MakeAsn1(n, e)

		// проверим, есть ли вообще такой публичный ключ
		userId, err := c.Single("SELECT user_id FROM users WHERE hex(public_key_0) = ?", publicKey).Int64()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if userId == 0 {
			return "", utils.ErrInfo(errors.New("incorrect public_key"))
		}

		// может быть юзер уже майнер?
		minerId, err := c.GetMinerId(userId)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		status := ""
		if minerId > 0 {
			status = "miner"
		} else {
			status = "user"
		}

		err = c.ExecSql(`DELETE FROM my_keys`)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		err = c.ExecSql(`INSERT INTO `+c.MyPrefix+`my_keys (public_key, status) VALUES ([hex], ?)`, publicKey, "approved")
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		err = c.ExecSql(`UPDATE `+c.MyPrefix+`my_table SET user_id = ?, miner_id = ?, status = ?`, userId, minerId, status)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
	}
	return `{"success":"success"}`, nil
}
func (p *Parser) NewAutoPaymentRollback() error {
	//fmt.Println(p.TxMap)
	affect, err := p.ExecSqlGetAffect("DELETE FROM auto_payments WHERE block_id = ? and sender = ?", p.BlockData.BlockId, p.TxUserID)
	if err != nil {
		return utils.ErrInfo(err)
	}

	err = p.rollbackAI("auto_payments", affect)
	if err != nil {
		return utils.ErrInfo(err)
	}
	return err
}