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

}
示例#2
0
文件: e_logout.go 项目: dzyk/dcoin-go
func (c *Controller) ELogout() (string, error) {

	if c.SessUserId == 0 {
		return utils.JsonAnswer("error", "empty SessUserId").String(), nil
	}
	c.sess.Delete("e_user_id")

	return utils.JsonAnswer("success", "success").String(), nil
}
示例#3
0
文件: e_login.go 项目: dzyk/dcoin-go
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
}
示例#4
0
文件: e_signup.go 项目: dzyk/dcoin-go
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
}
示例#5
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
}
示例#6
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
}
示例#7
0
func (c *Controller) EGetBalance() (string, error) {

	var myWallets []map[string]string
	myWallets, err := c.getMyWallets()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	html := ""
	for _, data := range myWallets {
		html += fmt.Sprintf("<strong>%v</strong> %v<br>", data["amount"], data["currency_name"])
	}

	return utils.JsonAnswer("html", html).String(), nil
}
示例#8
0
文件: update.go 项目: dzyk/dcoin-go
func (c *Controller) Update() (string, error) {

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

	ver, _, err := utils.GetUpdVerAndUrl(consts.UPD_AND_VER_URL)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	if len(ver) > 0 {
		newVersion := strings.Replace(c.Lang["new_version"], "[ver]", ver, -1)
		return utils.JsonAnswer(newVersion, "success").String(), nil
	}
	return "", nil
}
示例#9
0
func (c *Controller) SendToTheChat() (string, error) {

	c.r.ParseForm()
	message := c.r.FormValue("message")
	decryptMessage := c.r.FormValue("decrypt_message")
	sender := utils.StrToInt64(c.r.FormValue("sender"))
	receiver := utils.StrToInt64(c.r.FormValue("receiver"))
	lang := utils.StrToInt64(c.r.FormValue("lang"))
	room := utils.StrToInt64(c.r.FormValue("room"))
	// chatEncrypted == 1
	status := utils.StrToInt64(c.r.FormValue("status"))
	signTime := utils.StrToInt64(c.r.FormValue("sign_time"))
	signature := []byte(c.r.FormValue("signature"))

	data := utils.Int64ToByte(lang)
	data = append(data, utils.Int64ToByte(room)...)
	data = append(data, utils.Int64ToByte(receiver)...)
	data = append(data, utils.Int64ToByte(sender)...)
	data = append(data, utils.Int64ToByte(status)...)
	data = append(data, []byte(message)...)
	data = append(data, utils.Int64ToByte(signTime)...)
	data = append(data, []byte(signature)...)

	hash := utils.Md5(data)

	err := c.CheckChatMessage(message, sender, receiver, lang, room, status, signTime, signature)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	var chatId int64
	// на пуле сообщение сразу отобразится у всех
	if status == 1 {
		chatId, err = c.ExecSqlGetLastInsertId(`INSERT INTO chat (hash, time, lang, room, receiver, sender, status, enc_message, message, sign_time, signature) VALUES ([hex], ?, ?, ?, ?, ?, ?, ?, ?, ?, [hex])`, "id", hash, utils.Time(), lang, room, receiver, sender, 2, message, decryptMessage, signTime, signature)

	} else {
		chatId, err = c.ExecSqlGetLastInsertId(`INSERT INTO chat (hash, time, lang, room, receiver, sender, status, message, sign_time, signature) VALUES ([hex], ?, ?, ?, ?, ?, ?, ?, ?, [hex])`, "id", hash, utils.Time(), lang, room, receiver, sender, status, message, signTime, signature)
	}
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// даем команду рассыльщику, чтобы отправил всем хэш тр-ии сообщения
	utils.ChatNewTx <- chatId

	return utils.JsonAnswer("success", "success").String(), nil
}
示例#10
0
func (c *Controller) AvailableKeys() (string, error) {

	var email string
	if c.Community {
		// если это пул, то будет прислан email
		email = c.r.FormValue("email")
		if !utils.ValidateEmail(email) {
			return utils.JsonAnswer("Incorrect email", "error").String(), nil
		}
		// если мест в пуле нет, то просто запишем юзера в очередь
		pool_max_users, err := c.Single("SELECT pool_max_users FROM config").Int()
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
		if len(c.CommunityUsers) >= pool_max_users {
			err = c.ExecSql("INSERT INTO pool_waiting_list ( email, time, user_id ) VALUES ( ?, ?, ? )", email, utils.Time(), 0)
			if err != nil {
				return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
			}
			return utils.JsonAnswer(c.Lang["pool_is_full"], "error").String(), nil
		}
	}

	availablekey := &availablekey.AvailablekeyStruct{}
	availablekey.DCDB = c.DCDB
	availablekey.Email = email
	userId, publicKey, err := availablekey.GetAvailableKey()
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	if userId > 0 {
		c.sess.Set("user_id", userId)
		c.sess.Set("public_key", publicKey)
		log.Debug("user_id: %d", userId)
		log.Debug("public_key: %s", publicKey)
		return utils.JsonAnswer("success", "success").String(), nil
	}
	return utils.JsonAnswer("no_available_keys", "error").String(), nil
}
示例#11
0
func (c *Controller) AlertFromAdmin() (string, error) {

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

	alertMessage := ""
	alert, err := utils.GetHttpTextAnswer("http://dcoin.club/alert.json")
	if len(alert) > 0 {
		alertData := new(alertType)
		err = json.Unmarshal([]byte(alert), &alertData)
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
		}

		messageJson, err := json.Marshal(alertData.Message)
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
		}

		pub, err := utils.BinToRsaPubKey(utils.HexToBin(consts.ALERT_KEY))
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
		}
		err = rsa.VerifyPKCS1v15(pub, crypto.SHA1, utils.HashSha1(string(messageJson)), []byte(utils.HexToBin(alertData.Signature)))
		if err != nil {
			log.Error("%v", utils.ErrInfo(err))
		}

		if version.Compare(alertData.Message["version"], consts.VERSION, ">") {
			alertMessage = alertData.Message[utils.Int64ToStr(c.LangInt)]
			return utils.JsonAnswer(alertMessage, "success").String(), nil
		}
	}
	return ``, nil
}
示例#12
0
func (c *Controller) SendToPool() (string, error) {

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

	filesSign := c.r.FormValue("filesSign")

	poolUid := utils.StrToInt64(c.r.FormValue("poolUid"))
	data_, err := c.OneRow(`SELECT tcp_host, http_host FROM miners_data WHERE user_id = ?`, poolUid).String()
	tcpHost := data_["tcp_host"]
	httpHost := data_["http_host"]
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	conn, err := net.DialTimeout("tcp", tcpHost, 5*time.Second)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer conn.Close()

	conn.SetReadDeadline(time.Now().Add(240 * time.Second))
	conn.SetWriteDeadline(time.Now().Add(240 * time.Second))

	var data []byte
	data = append(data, utils.DecToBin(c.SessUserId, 5)...)
	data = append(data, utils.EncodeLengthPlusData(filesSign)...)

	if _, err := os.Stat(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_face.jpg"); err == nil {
		file, err := ioutil.ReadFile(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_face.jpg")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		data = append(data, utils.EncodeLengthPlusData(append(utils.DecToBin(0, 1), file...))...)
	}
	if _, err := os.Stat(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_profile.jpg"); err == nil {
		file, err := ioutil.ReadFile(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_profile.jpg")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		data = append(data, utils.EncodeLengthPlusData(append(utils.DecToBin(1, 1), file...))...)
	}
	if _, err := os.Stat(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.mp4"); err == nil {
		file, err := ioutil.ReadFile(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_user_video.mp4")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		data = append(data, utils.EncodeLengthPlusData(append(utils.DecToBin(2, 1), file...))...)
	}

	// тип данных
	_, err = conn.Write(utils.DecToBin(11, 1))
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// в 4-х байтах пишем размер данных, которые пошлем далее
	size := utils.DecToBin(len(data), 4)
	_, err = conn.Write(size)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// далее шлем сами данные
	_, err = conn.Write([]byte(data))
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// в ответ получаем статус
	buf := make([]byte, 1)
	_, err = conn.Read(buf)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	status := utils.BinToDec(buf)
	result := ""
	if status == 1 {
		result = utils.JsonAnswer("1", "success").String()
		c.ExecSql(`UPDATE `+c.MyPrefix+`my_table SET tcp_host = ?, http_host = ?`, tcpHost, httpHost)
	} else {
		result = utils.JsonAnswer("error", "error").String()
	}

	return result, nil
}
示例#13
0
func (c *Controller) UploadVideo() (string, error) {

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

	var binaryVideo []byte

	c.r.ParseMultipartForm(32 << 20)
	file, _, err := c.r.FormFile("file")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	videoBuffer := new(bytes.Buffer)
	_, err = io.Copy(videoBuffer, file)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer file.Close()
	binaryVideo = videoBuffer.Bytes()
	fmt.Println(c.r.MultipartForm.File["file"][0].Filename)
	fmt.Println(c.r.MultipartForm.File["file"][0].Header.Get("Content-Type"))
	fmt.Println(c.r.MultipartForm.Value["type"][0])

	var contentType, videoType string
	if _, ok := c.r.MultipartForm.File["file"]; ok {
		contentType = c.r.MultipartForm.File["file"][0].Header.Get("Content-Type")
	}
	if _, ok := c.r.MultipartForm.Value["type"]; ok {
		videoType = c.r.MultipartForm.Value["type"][0]
	}
	end := "mp4"
	switch contentType {
	case "video/mp4", "video/quicktime":
		end = "mp4"
	case "video/ogg":
		end = "ogv"
	case "video/webm":
		end = "webm"
	case "video/3gpp":

		fmt.Println("3gpp")
		conn, err := net.DialTimeout("tcp", "3gp.dcoin.club:8099", 5*time.Second)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		defer conn.Close()

		conn.SetReadDeadline(time.Now().Add(240 * time.Second))
		conn.SetWriteDeadline(time.Now().Add(240 * time.Second))

		// в 4-х байтах пишем размер данных, которые пошлем далее
		size := utils.DecToBin(len(videoBuffer.Bytes()), 4)
		_, err = conn.Write(size)
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// далее шлем сами данные
		_, err = conn.Write(videoBuffer.Bytes())
		if err != nil {
			return "", utils.ErrInfo(err)
		}

		// в ответ получаем размер данных, которые нам хочет передать сервер
		buf := make([]byte, 4)
		n, err := conn.Read(buf)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		log.Debug("dataSize buf: %x / get: %v", buf, n)

		// и если данных менее 10мб, то получаем их
		dataSize := utils.BinToDec(buf)
		var binaryBlock []byte
		log.Debug("dataSize: %v", dataSize)
		if dataSize < 10485760 && dataSize > 0 {
			binaryBlock = make([]byte, dataSize)
			//binaryBlock, err = ioutil.ReadAll(conn)
			_, err = io.ReadFull(conn, binaryBlock)
			if err != nil {
				return "", utils.ErrInfo(err)
			}
			log.Debug("len(binaryBlock):", len(binaryBlock))
			binaryVideo = binaryBlock
		}
	}

	log.Debug(videoType, end)

	var name string
	if videoType == "user_video" {
		name = "public/" + utils.Int64ToStr(c.SessUserId) + "_user_video." + end
	} else {
		x := strings.Split(videoType, "-")
		if len(x) < 2 {
			if err != nil {
				return "", utils.ErrInfo(err)
			}
		}
		name = "public/" + utils.Int64ToStr(c.SessUserId) + "_promised_amount_" + x[1] + "." + end
	}
	log.Debug(*utils.Dir + "/" + name)
	err = ioutil.WriteFile(*utils.Dir+"/"+name, binaryVideo, 0644)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return utils.JsonAnswer(string(utils.DSha256(binaryVideo)), "success").String(), nil
}
func (c *Controller) SendPromisedAmountToPool() (string, error) {

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

	filesSign := c.r.FormValue("filesSign")
	currencyId := utils.StrToInt64(c.r.FormValue("currencyId"))
	tcpHost, err := c.Single(`SELECT tcp_host FROM miners_data WHERE user_id = ?`, c.SessUserId).String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	conn, err := net.DialTimeout("tcp", tcpHost, 5*time.Second)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer conn.Close()

	conn.SetReadDeadline(time.Now().Add(240 * time.Second))
	conn.SetWriteDeadline(time.Now().Add(240 * time.Second))

	var data []byte
	data = append(data, utils.DecToBin(c.SessUserId, 5)...)
	data = append(data, utils.DecToBin(currencyId, 1)...)
	data = append(data, utils.EncodeLengthPlusData(filesSign)...)

	if _, err := os.Stat(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_promised_amount_" + utils.Int64ToStr(currencyId) + ".mp4"); err == nil {
		file, err := ioutil.ReadFile(*utils.Dir + "/public/" + utils.Int64ToStr(c.SessUserId) + "_promised_amount_" + utils.Int64ToStr(currencyId) + ".mp4")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		data = append(data, utils.EncodeLengthPlusData(append(utils.DecToBin(2, 1), file...))...)
	}

	// тип данных
	_, err = conn.Write(utils.DecToBin(12, 1))
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// в 4-х байтах пишем размер данных, которые пошлем далее
	size := utils.DecToBin(len(data), 4)
	_, err = conn.Write(size)
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// далее шлем сами данные
	_, err = conn.Write([]byte(data))
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// в ответ получаем статус
	buf := make([]byte, 1)
	_, err = conn.Read(buf)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	status := utils.BinToDec(buf)
	result := ""
	if status == 1 {
		result = utils.JsonAnswer("1", "success").String()
	} else {
		result = utils.JsonAnswer("error", "error").String()
	}

	return result, nil
}
示例#15
0
func (c *Controller) SignUpInPool() (string, error) {

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

	if !c.Community {
		return "", utils.JsonAnswer("Not pool", "error").Error()
	}

	c.r.ParseForm()

	var userId int64
	var codeSign string
	if c.SessUserId <= 0 {
		// запрос пришел с десктопного кошелька юзера
		codeSign = c.r.FormValue("code_sign")
		if !utils.CheckInputData(codeSign, "hex_sign") {
			return "", utils.JsonAnswer("Incorrect code_sign", "error").Error()
		}
		userId = utils.StrToInt64(c.r.FormValue("user_id"))
		if !utils.CheckInputData(userId, "int64") {
			return "", utils.JsonAnswer("Incorrect userId", "error").Error()
		}
		// получим данные для подписи
		var hash []byte

		RemoteAddr := utils.RemoteAddrFix(c.r.RemoteAddr)
		re := regexp.MustCompile(`(.*?):[0-9]+$`)
		match := re.FindStringSubmatch(RemoteAddr)
		if len(match) != 0 {
			RemoteAddr = match[1]
		}
		log.Debug("RemoteAddr %s", RemoteAddr)
		hash = utils.Md5(c.r.Header.Get("User-Agent") + RemoteAddr)
		log.Debug("hash %s", hash)

		forSign, err := c.GetDataAuthorization(hash)
		log.Debug("forSign: %v", forSign)
		publicKey, err := c.GetUserPublicKey(userId)
		log.Debug("publicKey: %x", publicKey)
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
		// проверим подпись
		resultCheckSign, err := utils.CheckSign([][]byte{[]byte(publicKey)}, forSign, utils.HexToBin([]byte(codeSign)), true)
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
		if !resultCheckSign {
			return "", utils.JsonAnswer("Incorrect codeSign", "error").Error()
		}
	} else {
		// запрос внутри пула
		userId = c.SessUserId
	}
	/*e:=c.r.FormValue("e")
	n:=c.r.FormValue("n")
	if len(e) == 0 || len(n) == 0 {
		result, _ := json.Marshal(map[string]string{"error": c.Lang["pool_error"]})
		return "", errors.New(string(result))
	}*/
	email := c.r.FormValue("email")
	if !utils.ValidateEmail(email) {
		return "", utils.JsonAnswer("Incorrect email", "error").Error()
	}
	nodePrivateKey := c.r.FormValue("node_private_key")
	if !utils.CheckInputData(nodePrivateKey, "private_key") {
		return "", utils.JsonAnswer("Incorrect private_key", "error").Error()
	}
	//publicKey := utils.MakeAsn1([]byte(n), []byte(e))
	log.Debug("3")

	// если мест в пуле нет, то просто запишем юзера в очередь
	pool_max_users, err := c.Single("SELECT pool_max_users FROM config").Int()
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	if len(c.CommunityUsers) >= pool_max_users {
		err = c.ExecSql("INSERT INTO pool_waiting_list ( email, time, user_id ) VALUES ( ?, ?, ? )", email, utils.Time(), userId)
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
		return "", utils.JsonAnswer(c.Lang["pool_is_full"], "error").Error()
	}

	// регистрируем юзера в пуле
	// вначале убедимся, что такой user_id у нас уже не зареган
	community, err := c.Single("SELECT user_id FROM community WHERE user_id  =  ?", userId).Int64()
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	if community != 0 {
		return utils.JsonAnswer(c.Lang["pool_user_id_is_busy"], "success").String(), nil
	}
	err = c.ExecSql("INSERT INTO community ( user_id ) VALUES ( ? )", userId)
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}

	schema_ := &schema.SchemaStruct{}
	schema_.DCDB = c.DCDB
	schema_.DbType = c.ConfigIni["db_type"]
	schema_.PrefixUserId = int(userId)
	schema_.GetSchema()

	prefix := utils.Int64ToStr(userId) + "_"
	minerId, err := c.GetMinerId(userId)
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	if minerId > 0 {
		err = c.ExecSql("INSERT INTO "+prefix+"my_table ( user_id, miner_id, status, email ) VALUES  (?, ?, ?, ?)", userId, minerId, "miner", email)
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
	} else {
		err = c.ExecSql("INSERT INTO "+prefix+"my_table ( user_id, status, email ) VALUES (?, ?, ?)", userId, "miner", email)
		if err != nil {
			return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
		}
	}

	publicKey, err := c.GetUserPublicKey(userId)
	err = c.ExecSql("INSERT INTO "+prefix+"my_keys ( public_key, status ) VALUES ( [hex], 'approved' )", utils.BinToHex(publicKey))
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	nodePublicKey, err := utils.GetPublicFromPrivate(nodePrivateKey)
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}
	err = c.ExecSql("INSERT INTO "+prefix+"my_node_keys ( private_key, public_key ) VALUES ( ?, [hex] )", nodePrivateKey, nodePublicKey)
	if err != nil {
		return "", utils.JsonAnswer(utils.ErrInfo(err), "error").Error()
	}

	c.sess.Delete("restricted")
	return utils.JsonAnswer(c.Lang["pool_sign_up_success"], "success").String(), nil
}