Exemplo n.º 1
0
func (c *Controller) DbInfoNodes() (string, error) {

	// стата по нодам
	q := ""
	if c.ConfigIni["db_type"] == "postgresql" {
		q = "SELECT DISTINCT ON (http_host) http_host FROM miners_data WHERE miner_id > 0  LIMIT 20"
	} else {
		q = "SELECT http_host FROM miners_data WHERE miner_id > 0  GROUP BY http_host LIMIT 20"
	}
	rows, err := c.Query(c.FormatQuery(q))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	var titles []string
	var nodesData []map[string]string
	for rows.Next() {
		var http_host string
		err = rows.Scan(&http_host)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		fmt.Println(http_host)
		jsonData, err := utils.GetHttpTextAnswer(http_host + "/ajax?controllerName=checkNode")
		if err != nil {
			continue
		}
		var jsonMap map[string]string
		err = json.Unmarshal([]byte(jsonData), &jsonMap)
		if err != nil {
			continue
		}
		if len(titles) == 0 {
			for k, _ := range jsonMap {
				titles = append(titles, k)
			}
		}
		jsonMap["host"] = http_host
		nodesData = append(nodesData, jsonMap)
	}
	fmt.Println("nodesData", nodesData)

	TemplateStr, err := makeTemplate("db_info_nodes", "dbInfoNodes", &DbInfoNodesPage{
		Lang:      c.Lang,
		Titles:    titles,
		NodesData: nodesData})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemplo n.º 2
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
}
Exemplo n.º 3
0
func CfProjects(chBreaker chan bool, chAnswer chan string) {
	defer func() {
		if r := recover(); r != nil {
			log.Error("daemon Recovered", r)
			panic(r)
		}
	}()

	const GoroutineName = "CfProjects"
	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 = 1800
	} else {
		d.sleepTime = 60
	}
	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, restart := d.dbLock()
		if restart {
			break BEGIN
		}
		if err != nil {
			if d.dPrintSleep(err, d.sleepTime) {
				break BEGIN
			}
			continue BEGIN
		}

		// гео-декодирование
		all, err := d.GetAll(`
				SELECT id,
							latitude,
							longitude
				FROM cf_projects
				WHERE geo_checked= 0
				`, -1)
		for _, cf_projects := range all {
			gmapData, err := utils.GetHttpTextAnswer("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + cf_projects["latitude"] + "," + cf_projects["longitude"] + "&sensor=true_or_false")
			if err != nil {
				if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			var gmap map[string][]map[string][]map[string]string
			json.Unmarshal([]byte(gmapData), &gmap)
			if len(gmap["results"]) > 1 && len(gmap["results"][len(gmap["results"])-2]["address_components"]) > 0 {
				country := gmap["results"][len(gmap["results"])-2]["address_components"][0]["long_name"]
				city := gmap["results"][len(gmap["results"])-2]["address_components"][1]["short_name"]
				err = d.ExecSql("UPDATE cf_projects SET country = ?, city = ?, geo_checked= 1 WHERE id = ?", country, city, cf_projects["id"])
				if err != nil {
					if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
						break BEGIN
					}
					continue BEGIN
				}
			}
		}

		// финансирование проектов
		cf_funding, err := d.GetAll(`
				SELECT  id,
							 project_id,
							 amount
				FROM cf_funding
				WHERE checked= 0
				`, -1)
		for _, data := range cf_funding {
			// отмечаем, чтобы больше не брать
			err = d.ExecSql("UPDATE cf_funding SET checked = 1 WHERE id = ?", data["id"])
			if err != nil {
				if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}
			// сколько собрано средств
			funding, err := d.Single("SELECT sum(amount) FROM cf_funding WHERE project_id  =  ? AND del_block_id  =  0", data["project_id"]).Float64()
			if err != nil {
				if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}

			// сколько всего фундеров
			countFunders, err := d.Single("SELECT count(id) FROM cf_funding WHERE project_id  = ? AND del_block_id  =  0 GROUP BY user_id", data["project_id"]).Int64()
			if err != nil {
				if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
					break BEGIN
				}
				continue BEGIN
			}

			// обновляем кол-во фундеров и собранные средства
			err = d.ExecSql("UPDATE cf_projects SET funding = ?, funders = ? WHERE id = ?", funding, countFunders, data["project_id"])
			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)
}
Exemplo n.º 4
0
func (a *AvailablekeyStruct) GetAvailableKey() (int64, string, error) {

	community, err := a.GetCommunityUsers()
	if err != nil {
		return 0, "", utils.ErrInfo(err)
	}
	// запрещено менять ключ таким методом если в my_table уже есть статус
	if len(community) == 0 {
		status, err := a.Single("SELECT status FROM my_table").String()
		if err != nil {
			return 0, "", utils.ErrInfo(err)
		}
		if status != "my_pending" {
			return 0, "", utils.ErrInfo(errors.New("my_table not null"))
		}
	}

	var keys []string
	for i := 0; i < 10; i++ {
		keysStr, err := utils.GetHttpTextAnswer("http://dcoin.club/keys")
		if err != nil {
			return 0, "", utils.ErrInfo(err)
		}
		//keysStr = strings.Replace(keysStr, "\n", "", -1)
		r, _ := regexp.Compile("(?s)-----BEGIN RSA PRIVATE KEY-----(.*?)-----END RSA PRIVATE KEY-----")
		keys = r.FindAllString(keysStr, -1)
		for i := range keys {
			j := rand.Intn(i + 1)
			keys[i], keys[j] = keys[j], keys[i]
		}
		if len(keys) > 0 {
			break
		} else {
			utils.Sleep(5)
		}
	}

	for _, key := range keys {
		userId, pubKey, err := a.checkAvailableKey(key)
		if err != nil {
			log.Error("%s", utils.ErrInfo(err)) // тут ошибка - это нормально
		}
		log.Debug("checkAvailableKey userId: %v", userId)
		if userId > 0 {
			// запишем приватный ключ в БД, чтобы можно было подписать тр-ию на смену ключа
			myPref := ""

			log.Debug("schema_ 0")
			if len(community) > 0 {
				schema_ := &schema.SchemaStruct{}
				schema_.DCDB = a.DCDB
				schema_.DbType = a.ConfigIni["db_type"]
				schema_.PrefixUserId = int(userId)
				schema_.GetSchema()
				myPref = utils.Int64ToStr(userId) + "_"
				err = a.ExecSql("INSERT INTO "+myPref+"my_table (user_id, status, email) VALUES (?, ?, ?)", userId, "waiting_set_new_key", a.Email)
				if err != nil {
					return 0, "", utils.ErrInfo(err)
				}
				err = a.ExecSql("INSERT INTO community ( user_id ) VALUES ( ? )", userId)
				if err != nil {
					return 0, "", utils.ErrInfo(err)
				}
			} else {
				err = a.ExecSql("UPDATE my_table SET user_id = ?, status = ?", userId, "waiting_set_new_key")
				if err != nil {
					return 0, "", utils.ErrInfo(err)
				}
			}
			log.Debug("schema_ 1")

			// пишем приватный в my_keys т.к. им будем подписывать тр-ию на смену ключа
			err = a.ExecSql("INSERT INTO "+myPref+"my_keys (private_key, public_key, status, block_id) VALUES (?, [hex], ?, ?)", key, pubKey, "approved", 1)
			if err != nil {
				return 0, "", utils.ErrInfo(err)
			}
			log.Debug("GenKeys 0")
			newPrivKey, newPubKey := utils.GenKeys()
			log.Debug("GenKeys 1")
			// сразу генерируем новый ключ и пишем приватный временно в my_keys, чтобы можно было выдавать юзеру для скачивания
			err = a.ExecSql("INSERT INTO "+myPref+"my_keys (private_key, public_key, status) VALUES (?, ?, ?)", newPrivKey, utils.HexToBin([]byte(newPubKey)), "my_pending")
			if err != nil {
				return 0, "", utils.ErrInfo(err)
			}
			log.Debug("return userId %d", userId)
			return userId, pubKey, nil
		}
	}
	return 0, "", nil
}
Exemplo n.º 5
0
func (c *Controller) Upgrade6() (string, error) {

	log.Debug("Upgrade6")

	var hostType string

	hostData, err := c.OneRow("SELECT http_host, tcp_host FROM " + c.MyPrefix + "my_table").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	// в режиме пула выдаем только хост ноды
	log.Debug("c.Community: %v", c.Community)
	log.Debug("c.PoolAdminUserId: %v", c.PoolAdminUserId)
	if c.Community /*&& len(data["http_host"]) == 0 && len(data["tcp_host"]) == 0*/ {
		hostType = "pool"
		hostData, err = c.OneRow("SELECT http_host, tcp_host FROM miners_data WHERE user_id  =  ?", c.PoolAdminUserId).String()
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		if len(hostData) == 0 {
			hostData["http_host"] = "null http_host in miners_data"
			hostData["tcp_host"] = "null tcp_host in miners_data"
		}
	} else {
		// если смогли подключиться из вне
		ip, err := utils.GetHttpTextAnswer("http://api.ipify.org")
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		/*httpHost, err := c.Single("SELECT http_host FROM "+c.MyPrefix+"my_table").String()
		if err!=nil {
			return "", utils.ErrInfo(err)
		}
		port := "8089"
		if len(httpHost) > 0 {
			re := regexp.MustCompile(`https?:\/\/(?:[0-9a-z\_\.\-]+):([0-9]+)`)
			match := re.FindStringSubmatch(httpHost)
			if len(match) != 0 {
				port = match[1];
			}
		}*/
		conn, err := net.DialTimeout("tcp", ip+":8089", 3*time.Second)
		log.Debug("ip: %v", ip)
		if err != nil {
			// если не смогли подключиться, то в JS будем искать рабочий пул и региться на нем. и дадим юзеру указать другие хост:ip
			hostType = "findPool"

		} else {
			hostType = "normal"
			defer conn.Close()
			hostData["http_host"] = ip + ":8089"
			hostData["tcp_host"] = ip + ":8088"
		}
	}

	// проверим, есть ли необработанные ключи в локальной табле
	nodePrivateKey, err := c.Single("SELECT private_key FROM " + c.MyPrefix + "my_node_keys WHERE block_id  =  0").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	if len(nodePrivateKey) == 0 {
		//  сгенерим ключ для нода
		priv, pub := utils.GenKeys()
		err = c.ExecSql("INSERT INTO "+c.MyPrefix+"my_node_keys ( public_key, private_key ) VALUES ( [hex], ? )", pub, priv)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		nodePrivateKey = priv
	}

	var profileHash, faceHash, videoHash string

	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)
		}
		faceHash = string(utils.DSha256(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)
		}
		profileHash = string(utils.DSha256(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)
		}
		videoHash = string(utils.DSha256(file))
	}

	text, err := utils.GetHttpTextAnswer("http://dcoin.club/pools")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	var pools_ []string
	err = json.Unmarshal([]byte(text), &pools_)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	log.Debug("pools: %v", pools_)
	rows, err := c.Query(c.FormatQuery(`
			SELECT user_id, http_host
			FROM miners_data
			WHERE user_id IN (` + strings.Join(pools_, ",") + `)`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	defer rows.Close()
	pools := make(map[string]string)
	for rows.Next() {
		var user_id, http_host string
		err = rows.Scan(&user_id, &http_host)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		pools[user_id] = http_host
	}
	poolsJs := ""
	for userId, httpHost := range pools {
		poolsJs = poolsJs + "[" + userId + ",'" + httpHost + "'],"
	}
	poolsJs = poolsJs[:len(poolsJs)-1]

	videoUrlId, err := c.Single("SELECT video_url_id FROM " + c.MyPrefix + "my_table").String()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

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

	TemplateStr, err := makeTemplate("upgrade_6", "upgrade6", &upgrade6Page{
		Alert:           c.Alert,
		Lang:            c.Lang,
		SaveAndGotoStep: saveAndGotoStep,
		UpgradeMenu:     upgradeMenu,
		ShowSignData:    c.ShowSignData,
		SignData:        "",
		CountSignArr:    c.CountSignArr,
		HttpHost:        hostData["http_host"],
		TcpHost:         hostData["tcp_host"],
		Community:       c.Community,
		HostType:        hostType,
		ProfileHash:     profileHash,
		FaceHash:        faceHash,
		VideoHash:       videoHash,
		NodePrivateKey:  nodePrivateKey,
		Pools:           template.JS(poolsJs),
		UserId:          c.SessUserId,
		VideoUrlId:      videoUrlId,
		Mobile:          utils.Mobile()})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}
Exemplo n.º 6
0
func (c *Controller) NewPromisedAmount() (string, error) {

	txType := "NewPromisedAmount"
	txTypeId := utils.TypeInt(txType)
	timeNow := time.Now().Unix()

	navigate := "promisedAmountList"
	if len(c.Navigate) > 0 {
		navigate = c.Navigate
	}

	rows, err := c.Query(c.FormatQuery(`
		SELECT id,
					 name,
					 full_name,
					 max_other_currencies
		FROM currency WHERE id != 1
		ORDER BY full_name`))
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	currencyList := make(map[int64]map[string]string)
	currencyListName := make(map[int64]string)
	defer rows.Close()
	for rows.Next() {
		var id int64
		var name, full_name, max_other_currencies string
		err = rows.Scan(&id, &name, &full_name, &max_other_currencies)
		if err != nil {
			return "", utils.ErrInfo(err)
		}
		currencyList[id] = map[string]string{"id": utils.Int64ToStr(id), "name": name, "full_name": full_name, "max_other_currencies": max_other_currencies}
		currencyListName[id] = name
	}

	paymentSystems, err := c.GetPaymentSystems()
	if err != nil {
		return "", utils.ErrInfo(err)
	}

	maxPromisedAmounts, err := c.GetMap(`SELECT currency_id, amount FROM max_promised_amounts WHERE block_id = 1`, "currency_id", "amount")
	maxPromisedAmountsMaxBlock, err := c.GetMap(`SELECT currency_id, amount FROM max_promised_amounts WHERE block_id = (SELECT max(block_id) FROM max_promised_amounts ) OR block_id = 0`, "currency_id", "amount")
	for k, v := range maxPromisedAmountsMaxBlock {
		maxPromisedAmounts[k] = v
	}

	// валюта, которая выбрана в селект-боксе
	currencyId := int64(72)

	limitsText := strings.Replace(c.Lang["limits_text"], "[limit]", utils.Int64ToStr(c.Variables.Int64["limit_promised_amount"]), -1)
	limitsText = strings.Replace(limitsText, "[period]", c.Periods[c.Variables.Int64["limit_promised_amount_period"]], -1)

	countPs := []int{1, 2, 3, 4, 5}

	tcpHostPort, err := c.Single(`SELECT tcp_host from miners_data WHERE user_id = ?`, c.SessUserId).String()
	tcpHost, _, _ := net.SplitHostPort(tcpHostPort)
	nodeIp, err := net.ResolveIPAddr("ip4", tcpHost)
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	myIp, err := utils.GetHttpTextAnswer("http://api.ipify.org")
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	mode := "normal"
	if myIp != nodeIp.String() {
		mode = "pool"
	}
	fmt.Println(nodeIp.String(), myIp)

	TemplateStr, err := makeTemplate("new_promised_amount", "newPromisedAmount", &newPromisedAmountPage{
		Alert:              c.Alert,
		Lang:               c.Lang,
		CountSignArr:       c.CountSignArr,
		ShowSignData:       c.ShowSignData,
		UserId:             c.SessUserId,
		TimeNow:            timeNow,
		TxType:             txType,
		TxTypeId:           txTypeId,
		SignData:           "",
		ConfigCommission:   c.ConfigCommission,
		Navigate:           navigate,
		IncNavigate:        c.Navigate,
		CurrencyId:         currencyId,
		CurrencyList:       currencyList,
		CurrencyListName:   currencyListName,
		MaxPromisedAmounts: maxPromisedAmounts,
		LimitsText:         limitsText,
		PaymentSystems:     paymentSystems,
		Mobile:             utils.Mobile(),
		Mode:               mode,
		CountPs:            countPs})
	if err != nil {
		return "", utils.ErrInfo(err)
	}
	return TemplateStr, nil
}