func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewMaxOtherCurrencies" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // json data txSlice = append(txSlice, []byte(`{"1":"1000", "72":500}`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "ChangeArbitrationDaysRefund" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) // arbitration_days_refund txSlice = append(txSlice, []byte("150")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "ChangeKeyActive" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) // secret txSlice = append(txSlice, []byte("156516546572676276827")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "DelPromisedAmount" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // promised_amount_id txSlice = append(txSlice, []byte("4")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "Abuses" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // message txSlice = append(txSlice, []byte(`{"1":"fdfdsfdd", "2":"fsdfkj43 43 34"}`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func (p *Parser) NewUserFront() error { log.Debug("NewUserFront") err := p.generalCheck() if err != nil { return p.ErrInfo(err) } // является ли данный юзер майнером err = p.checkMiner(p.TxUserID) if err != nil { return p.ErrInfo(err) } // прошло ли 30 дней с момента регистрации майнера err = p.checkMinerNewbie() if err != nil { return p.ErrInfo(err) } // чтобы не записали слишком мелкий или слишком крупный ключ if !utils.CheckInputData(p.TxMap["public_key_hex"], "public_key") { return utils.ErrInfo(fmt.Errorf("incorrect public_key %s", p.TxMap["public_key_hex"])) } // публичный ключ должен быть без паролей if ok, _ := regexp.MatchString("DEK-Info: (.+),(.+)", string(p.TxMap["public_key"])); ok { return p.ErrInfo("incorrect public_key") } forSign := fmt.Sprintf("%s,%s,%s,%s", p.TxMap["type"], p.TxMap["time"], p.TxMap["user_id"], p.TxMap["public_key_hex"]) CheckSignResult, err := utils.CheckSign(p.PublicKeys, forSign, p.TxMap["sign"], false) if err != nil { return p.ErrInfo(err) } if !CheckSignResult { return p.ErrInfo("incorrect sign") } // один ключ не может быть у двух юзеров num, err := p.DCDB.Single("SELECT count(user_id) FROM users WHERE hex(public_key_0) = ? OR hex(public_key_1) = ? OR hex(public_key_2) = ?", p.TxMap["public_key_hex"], p.TxMap["public_key_hex"], p.TxMap["public_key_hex"]).Int() if num > 0 { return p.ErrInfo("exists public_key") } err = p.getAdminUserId() if err != nil { return p.ErrInfo(err) } if utils.BytesToInt64(p.TxMap["user_id"]) == p.AdminUserId { err = p.limitRequest(1000, "new_user", 86400) } else { err = p.limitRequest(p.Variables.Int64["limit_new_user"], "new_user", p.Variables.Int64["limit_new_user_period"]) } if err != nil { return p.ErrInfo(err) } return nil }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewUser" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // public_key txSlice = append(txSlice, utils.HexToBin([]byte("30820122300d06092a864886f70d01010105000382010f003082010a0282010100ae7797b5c16358862f083bb26cde86b233ba97c48087df44eaaf88efccfe554bf51df8dc7e99072cbe433933f1b87aa9ef62bd5d49dc40e75fe398426c727b0773ea9e4d88184d64c1aa561b1cdf78abe07ca5d23711c403f58abf30d41f4b96161649a91a95818d9d482e8fa3f91829abce3d80f6fc3708ce23f6841bb4a8bae301b23745fce5134420fec0519a081f162d16e4dd0da2e8869b5b67122a1fb7e9bcdb8b2512d1edabdb271bee190563b36a66f5498f50d2fc7202ad2f43b90f860428d5ecd67973900d9997475d4e1a1e4c56b44411cc4b5e9c660fe23fdcd5ab956a834fa05a4ecac9d815143d84993c9424d86379b6f76e3be9aeaaff48fb0203010001)"))) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewMiner." txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) //race txSlice = append(txSlice, []byte("1")) //country txSlice = append(txSlice, []byte("1")) //latitude txSlice = append(txSlice, []byte("55")) //longitude txSlice = append(txSlice, []byte("55")) //host txSlice = append(txSlice, []byte("http://55.55.55.55/")) //face_coords txSlice = append(txSlice, []byte("[[118,275],[241,274],[39,274],[316,276],[180,364],[182,430],[181,490],[93,441],[259,433]]")) //profile_coords txSlice = append(txSlice, []byte("[[289,224],[148,216],[172,304],[123,239],[328,261],[305,349]]")) //face_hash txSlice = append(txSlice, []byte("face_hash")) //profile_hash txSlice = append(txSlice, []byte("profile_hash")) //video_type txSlice = append(txSlice, []byte("youtube")) //video_url_id txSlice = append(txSlice, []byte("video_url_id")) //node_public_key txSlice = append(txSlice, []byte("node_public_key")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "CfProjectData" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("4")) //project_id txSlice = append(txSlice, []byte("1")) //lang_id txSlice = append(txSlice, []byte("45")) //blurb_img txSlice = append(txSlice, []byte("http://i.imgur.com/YRCoVnc.jpg")) //head_img txSlice = append(txSlice, []byte("http://i.imgur.com/YRCoVnc.jpg")) //description_img txSlice = append(txSlice, []byte("http://i.imgur.com/YRCoVnc.jpg")) //picture txSlice = append(txSlice, []byte("http://i.imgur.com/YRCoVnc.jpg")) //video_type txSlice = append(txSlice, []byte("youtube")) //video_url_id txSlice = append(txSlice, []byte("X-_fg47G5yf-_f")) //news_img txSlice = append(txSlice, []byte("http://i.imgur.com/YRCoVnc.jpg")) //links txSlice = append(txSlice, []byte(`[["http:\/\/goo.gl\/fnfh1Dg",1,532,234,0],["http:\/\/goo.gl\/28Fh4h",1355,1344,2222,66]]`)) //hide txSlice = append(txSlice, []byte("1")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { /* Currency map[string][]float64 `json:"currency"` Referral map[string]int64 `json:"referral"` Admin int64 `json:"admin"` */ f := tests_utils.InitLog() defer f.Close() txType := "VotesComplex" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 newPct := new(vComplex) newPct.Currency = make(map[string][]float64) newPct.Referral = make(map[string]int64) newPct.Currency["1"] = []float64{0.0000000760368, 0.0000000497405, 1000, 55, 10} newPct.Currency["33"] = []float64{0.0000000760368, 0.0000000497405, 1000, 55, 10} newPct.Currency["2"] = []float64{0.0000000760368, 0.0000000497405, 1000, 55, 10} newPct.Referral["first"] = 30 newPct.Referral["second"] = 0 newPct.Referral["third"] = 30 newPct.Admin = 100 newPctJson, _ := json.Marshal(newPct) //newPct1:=new(vComplex) //err := json.Unmarshal([]byte(`{"currency":{"1":[7.60368e-08,4.97405e-08,1000,55,10],"2":[7.60368e-08,4.97405e-08,1000,55,10],"33":[7.60368e-08,4.97405e-08,1000,55,10]},"referral":{"first":30,"second":0,"third":30},"admin":100}`), &newPct1) //fmt.Println(newPct1) //fmt.Println(err) var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, userId) // newPctJson txSlice = append(txSlice, []byte(newPctJson)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f, err := os.OpenFile("dclog.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777) defer f.Close() //log.SetOutput(f) log.SetOutput(io.MultiWriter(f, os.Stdout)) log.SetFlags(log.LstdFlags | log.Lshortfile) txType := "Mining" txTime := "1406545931" userId := []byte("2") var blockId int64 = 123924 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, userId) // promised_amount_id txSlice = append(txSlice, []byte(`26`)) // amount txSlice = append(txSlice, []byte(`6`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) dir, err := utils.GetCurrentDir() if err != nil { fmt.Println(err) } configIni_, err := config.NewConfig("ini", dir+"/config.ini") if err != nil { fmt.Println(err) } configIni, err := configIni_.GetSection("default") db := utils.DbConnect(configIni) // делаем снимок БД в виде хэшей до начала тестов hashesStart, err := tests_utils.AllHashes(db) err = tests_utils.MakeTest(txSlice, blockData, txType, hashesStart, db, "work") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "SendDc" txTime := "1409288580" userId := []byte("2") var blockId int64 = 10000 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, userId) // to_user_id txSlice = append(txSlice, []byte("2")) // currency_id txSlice = append(txSlice, []byte("72")) // amount txSlice = append(txSlice, []byte("8")) // commission txSlice = append(txSlice, []byte("0.1")) /* for i:=0; i<5; i++ { txSlice = append(txSlice, []byte("0")) } for i:=0; i<5; i++ { txSlice = append(txSlice, []byte("0")) }*/ // comment txSlice = append(txSlice, []byte("1111111111111111111111111111111111")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewCfProject" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("4")) //currency_id txSlice = append(txSlice, []byte("72")) //amount txSlice = append(txSlice, []byte("5000")) //end_time txSlice = append(txSlice, []byte("1427383713")) //latitude txSlice = append(txSlice, []byte("39.94801")) //langitude txSlice = append(txSlice, []byte("39.94801")) //category txSlice = append(txSlice, []byte("1")) //project_currency_name txSlice = append(txSlice, []byte("0VVDDDF")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewPromisedAmount." txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // currency_id txSlice = append(txSlice, []byte("72")) // amount txSlice = append(txSlice, []byte("1000")) // video_type txSlice = append(txSlice, []byte("youtube")) // video_url_id txSlice = append(txSlice, []byte("fdfdfd")) // payment_systems_ids txSlice = append(txSlice, []byte("11,55,88")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewForexOrder" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, userId) // sell_currency_id txSlice = append(txSlice, []byte("1")) // sell_rate txSlice = append(txSlice, []byte("0.1")) // amount txSlice = append(txSlice, []byte("1")) // buy_currency_id txSlice = append(txSlice, []byte("72")) // commission txSlice = append(txSlice, []byte("0")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "MoneyBackRequest" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) // order_id txSlice = append(txSlice, []byte("1")) // arbitrator_enc_text for i := 0; i < 5; i++ { txSlice = append(txSlice, []byte("2222222222222222")) } // seller_enc_text txSlice = append(txSlice, []byte("3333333333333333")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f, err := os.OpenFile("dclog.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777) defer f.Close() //log.SetOutput(f) log.SetOutput(io.MultiWriter(f, os.Stdout)) log.SetFlags(log.LstdFlags | log.Lshortfile) txType := "Mining" txTime := "1406545938" userId := []byte("105") var blockId int64 = 123925 promised_amount_id := "24" amount := "5.69" var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, userId) // promised_amount_id txSlice = append(txSlice, []byte(promised_amount_id)) // amount txSlice = append(txSlice, []byte(amount)) dataForSign := fmt.Sprintf("%v,%v,%s,%s,%s", utils.TypeInt(txType), txTime, userId, promised_amount_id, amount) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err = tests_utils.MakeFrontTest(txSlice, utils.StrToInt64(txTime), dataForSign, txType, utils.BytesToInt64(userId), "", blockId) if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "AdminSpots" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // example_spots txSlice = append(txSlice, []byte("example_spots")) // segments txSlice = append(txSlice, []byte("segments")) // tolerances txSlice = append(txSlice, []byte("tolerances")) // compatibility txSlice = append(txSlice, []byte("compatibility")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "AdminNewVersion" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // soft_type txSlice = append(txSlice, []byte("php")) // version txSlice = append(txSlice, []byte("0.0.99a")) // file txSlice = append(txSlice, []byte("file")) // format txSlice = append(txSlice, []byte("zip")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "CfSendDc" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) //project_id txSlice = append(txSlice, []byte("11")) //amount txSlice = append(txSlice, []byte("100")) //commission txSlice = append(txSlice, []byte("5")) //comment txSlice = append(txSlice, []byte(`ORDER #15155 а"))в"))ы"))А"))в"))ы"))А"))ы"))в"))а"))в"))ы"))`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "ChangeGeolocation" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) // latitude txSlice = append(txSlice, []byte("55.66998")) // longitude txSlice = append(txSlice, []byte("11.66998")) // country txSlice = append(txSlice, []byte("12")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "ChangePrimaryKey" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var bin_public_key_pack []byte bin_public_key_pack = append(bin_public_key_pack, utils.EncodeLengthPlusData(utils.HexToBin([]byte("111111111")))...) bin_public_key_pack = append(bin_public_key_pack, utils.EncodeLengthPlusData(utils.HexToBin(([]byte(""))))...) bin_public_key_pack = append(bin_public_key_pack, utils.EncodeLengthPlusData(utils.HexToBin([]byte("")))...) var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) // public_keys txSlice = append(txSlice, []byte(bin_public_key_pack)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "NewSeller" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) //arbitration_trust_list \[[0-9]{1,10}(,[0-9]{1,10}){0,100}\] txSlice = append(txSlice, []byte("[1,2,3,6,4,91573]")) //arbitration_days_refund txSlice = append(txSlice, []byte("30")) //holdback_pct_array \[\"[0-9]{1,3}(\.[0-9]{2})?\"(,\"[0-9]{1,3}(\.[0-9]{2}\")?){3}\] txSlice = append(txSlice, []byte(`["100.00", "90.55", "0.00"]`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "CfComment" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("1")) //project_id txSlice = append(txSlice, []byte("1")) //lang_id txSlice = append(txSlice, []byte("1")) //comment txSlice = append(txSlice, []byte(`К"))о"))м"))м"))е"))н"))т)) http://google.com/ 54fds56f4sd`)) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func main() { f := tests_utils.InitLog() defer f.Close() txType := "AdminChangePrimaryKey" txTime := "1427383713" userId := []byte("2") var blockId int64 = 128008 var txSlice [][]byte // hash txSlice = append(txSlice, []byte("1111111111")) // type txSlice = append(txSlice, utils.Int64ToByte(utils.TypeInt(txType))) // time txSlice = append(txSlice, []byte(txTime)) // user_id txSlice = append(txSlice, []byte("91573")) // for_user_id txSlice = append(txSlice, []byte("91573")) // public_key txSlice = append(txSlice, []byte("ParseData::encode_length_plus_data(hextobin(423423423))")) // sign txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")) blockData := new(utils.BlockData) blockData.BlockId = blockId blockData.Time = utils.StrToInt64(txTime) blockData.UserId = utils.BytesToInt64(userId) err := tests_utils.MakeTest(txSlice, blockData, txType, "work_and_rollback") if err != nil { fmt.Println(err) } }
func Exchange(chBreaker chan bool, chAnswer chan string) { defer func() { if r := recover(); r != nil { log.Error("daemon Recovered", r) panic(r) } }() const GoroutineName = "Exchange" 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 } BEGIN: for { log.Info(GoroutineName) MonitorDaemonCh <- []string{GoroutineName, utils.Int64ToStr(utils.Time())} // проверим, не нужно ли нам выйти из цикла if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) { break BEGIN } blockId, err := d.GetConfirmedBlockId() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } var myPrefix string community, err := d.GetCommunityUsers() if len(community) > 0 { adminUserId, err := d.GetPoolAdminUserId() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } myPrefix = utils.Int64ToStr(adminUserId) + "_" } else { myPrefix = "" } eConfig, err := d.GetMap(`SELECT * FROM e_config`, "name", "value") if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } confirmations := utils.StrToInt64(eConfig["confirmations"]) mainDcAccount := utils.StrToInt64(eConfig["main_dc_account"]) // все валюты, с которыми работаем currencyList, err := utils.EGetCurrencyList() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } // ++++++++++++ reduction ++++++++++++ // максимальный номер блока для процентов. Чтобы брать только новые maxReductionBlock, err := d.Single(`SELECT max(block_id) FROM e_reduction`).Int64() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } // если есть свежая reduction, то нужно остановить торги reduction, err := d.Single(`SELECT block_id FROM reduction WHERE block_id > ? and pct > 0`, maxReductionBlock).Int64() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } if reduction > 0 { err = d.ExecSql(`INSERT INTO e_reduction_lock (time) VALUES (?)`, utils.Time()) if err != nil { log.Error("%v", utils.ErrInfo(err)) } } // если уже прошло 10 блоков с момента обнаружения reduction, то производим сокращение объема монет rows, err := d.Query(d.FormatQuery(`SELECT pct, currency_id, time, block_id FROM reduction WHERE block_id > ? AND block_id < ?`), maxReductionBlock, blockId-confirmations) if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } for rows.Next() { var pct float64 var currencyId, rTime, blockId int64 err = rows.Scan(&pct, ¤cyId, &rTime, &blockId) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } // $k = (100-$row['pct'])/100; k := (100 - pct) / 100 // уменьшаем все средства на счетах err = d.ExecSql(`UPDATE e_wallets SET amount = amount * ? WHERE currency_id = ?`, k, currencyId) // уменьшаем все средства на вывод err = d.ExecSql(`UPDATE e_withdraw SET amount = amount * ? WHERE currency_id = ? AND close_time = 0`, k, currencyId) // уменьшаем все ордеры на продажу err = d.ExecSql(`UPDATE e_orders SET amount = amount * ?, begin_amount = begin_amount * ? WHERE sell_currency_id = ?`, k, k, currencyId) err = d.ExecSql(`INSERT INTO e_reduction ( time, block_id, currency_id, pct ) VALUES ( ?, ?, ?, ? )`, rTime, blockId, currencyId, pct) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } } rows.Close() // ++++++++++++ DC ++++++++++++ /* * Важно! отключать в кроне при обнулении данных в БД * * 1. Получаем инфу о входящих переводах и начисляем их на счета юзеров * 2. Обновляем проценты * 3. Чистим кол-во отправленных смс-ок * */ nodePrivateKey, err := d.GetNodePrivateKey(myPrefix) if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } /* * Получаем инфу о входящих переводах и начисляем их на счета юзеров * */ // если всё остановлено из-за найденного блока с reduction, то входящие переводы не обрабатываем reductionLock, err := utils.EGetReductionLock() if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } if reductionLock > 0 { if d.dPrintSleep(utils.ErrInfo("reductionLock"), d.sleepTime) { break BEGIN } continue BEGIN } rows, err = d.Query(d.FormatQuery(` SELECT amount, id, block_id, type_id, currency_id, to_user_id, time, comment, comment_status FROM my_dc_transactions WHERE type = 'from_user' AND block_id < ? AND exchange_checked = 0 AND status = 'approved' AND to_user_id = ? ORDER BY id DESC`), blockId-confirmations, mainDcAccount) if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } for rows.Next() { var amount float64 var id, blockId, typeId, currencyId, toUserId, txTime int64 var comment, commentStatus string err = rows.Scan(&amount, &id, &blockId, &typeId, ¤cyId, &toUserId, &txTime, &comment, &commentStatus) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } // отметим exchange_checked=1, чтобы больше не брать эту тр-ию err = d.ExecSql(`UPDATE my_dc_transactions SET exchange_checked = 1 WHERE id = ?`, id) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } // вначале нужно проверить, точно ли есть такой перевод в блоке binaryData, err := d.Single(`SELECT data FROM block_chain WHERE id = ?`, blockId).Bytes() if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } p := new(dcparser.Parser) p.DCDB = d.DCDB p.BinaryData = binaryData p.ParseDataLite() for _, txMap := range p.TxMapArr { // пропускаем все ненужные тр-ии if utils.BytesToInt64(txMap["type"]) != utils.TypeInt("SendDc") { continue } log.Debug("md5hash %s", txMap["md5hash"]) // если что-то случится с таблой my_dc_transactions, то все ввода на биржу будут зачислены по новой // поэтому нужно проверять e_adding_funds exists, err := d.Single(`SELECT id FROM e_adding_funds WHERE hex(tx_hash) = ?`, string(txMap["md5hash"])).Int64() if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } log.Debug("exists %d", exists) if exists != 0 { continue } log.Debug("user_id = %d / typeId = %d / currency_id = %d / currencyId = %d / amount = %f / amount = %f / comment = %s / comment = %s / to_user_id = %d / toUserId = %d ", utils.BytesToInt64(txMap["user_id"]), typeId, utils.BytesToInt64(txMap["currency_id"]), currencyId, utils.BytesToFloat64(txMap["amount"]), amount, string(utils.BinToHex(txMap["comment"])), comment, utils.BytesToInt64(txMap["to_user_id"]), toUserId) // сравнение данных из таблы my_dc_transactions с тем, что в блоке if utils.BytesToInt64(txMap["user_id"]) == typeId && utils.BytesToInt64(txMap["currency_id"]) == currencyId && utils.BytesToFloat64(txMap["amount"]) == amount && string(utils.BinToHex(txMap["comment"])) == comment && utils.BytesToInt64(txMap["to_user_id"]) == toUserId { decryptedComment := comment if commentStatus == "encrypted" { // расшифруем коммент block, _ := pem.Decode([]byte(nodePrivateKey)) if block == nil || block.Type != "RSA PRIVATE KEY" { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } private_key, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } decryptedComment_, err := rsa.DecryptPKCS1v15(rand.Reader, private_key, utils.HexToBin(comment)) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } decryptedComment = string(decryptedComment_) // запишем расшифрованный коммент, чтобы потом можно было найти перевод в ручном режиме err = d.ExecSql("UPDATE "+myPrefix+"my_dc_transactions SET comment = ?, comment_status = 'decrypted' WHERE id = ?", decryptedComment, id) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } } // возможно юзер сделал перевод в той валюте, которая у нас на бирже еще не торгуется if len(currencyList[currencyId]) == 0 { log.Error("currencyId %d not trading", currencyId) continue } // возможно, что чуть раньше было reduction, а это значит, что все тр-ии, // которые мы ещё не обработали и которые были До блока с reduction нужно принимать с учетом reduction // т.к. средства на нашем счете уже урезались, а вот те, что после reduction - остались в том виде, в котором пришли lastReduction, err := d.OneRow("SELECT block_id, pct FROM reduction WHERE currency_id = ? ORDER BY block_id", currencyId).Int64() if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } if blockId <= lastReduction["block_id"] { // сумму с учетом reduction k0 := (100 - lastReduction["pct"]) / 100 amount = amount * float64(k0) } // начисляем средства на счет того, чей id указан в комменте r, _ := regexp.Compile(`(?i)\s*#\s*([0-9]+)\s*`) user := r.FindStringSubmatch(decryptedComment) if len(user) == 0 { log.Error("len(user) == 0") continue } log.Debug("user %s", user[1]) // user_id с биржевой таблы uid := utils.StrToInt64(user[1]) userAmountAndProfit := utils.EUserAmountAndProfit(uid, currencyId) newAmount_ := userAmountAndProfit + amount utils.UpdEWallet(uid, currencyId, utils.Time(), newAmount_, true) // для отчетности запишем в историю err = d.ExecSql(` INSERT INTO e_adding_funds ( user_id, currency_id, time, amount, tx_hash ) VALUES ( ?, ?, ?, ?, ? )`, uid, currencyId, txTime, amount, string(txMap["md5hash"])) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } } } } rows.Close() /* * Обновляем проценты * */ // максимальный номер блока для процентов. Чтобы брать только новые maxPctBlock, err := d.Single(`SELECT max(block_id) FROM e_user_pct`).Int64() log.Debug(`SELECT time, block_id, currency_id, user FROM pct WHERE block_id < ` + utils.Int64ToStr(blockId-confirmations) + ` AND block_id > ` + utils.Int64ToStr(maxPctBlock)) rows, err = d.Query(d.FormatQuery(`SELECT time, block_id, currency_id, user FROM pct WHERE block_id < ? AND block_id > ?`), blockId-confirmations, maxPctBlock) if err != nil { if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } for rows.Next() { var pct float64 var pTime, blockId, currencyId int64 err = rows.Scan(&pTime, &blockId, ¤cyId, &pct) if err != nil { rows.Close() if d.dPrintSleep(utils.ErrInfo(err), d.sleepTime) { break BEGIN } continue BEGIN } d.ExecSql(` INSERT INTO e_user_pct ( time, block_id, currency_id, pct ) VALUES ( ?, ?, ?, ? )`, pTime, blockId, currencyId, pct) } rows.Close() if d.dSleep(d.sleepTime) { break BEGIN } } log.Debug("break BEGIN %v", GoroutineName) }
/** Обработка данных (блоков или транзакций), пришедших с гейта. Только проверка. */ 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 AutoUpdate(chBreaker chan bool, chAnswer chan string) { defer func() { if r := recover(); r != nil { log.Error("daemon Recovered", r) panic(r) } }() GoroutineName := "AutoUpdate" 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 } config, err := d.GetNodeConfig() if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } if config["auto_update"] == "1" { updTime, _ := ioutil.ReadFile(*utils.Dir + "/auto_update") log.Debug("updTime %v / ", utils.BytesToInt64(updTime)) //fmt.Println(utils.BytesToInt64(updTime)) if utils.Time()-utils.BytesToInt64(updTime) < int64(d.sleepTime) { log.Debug("sleepTime") //fmt.Println("sleepTime") if d.dSleep(d.sleepTime) { break BEGIN } continue BEGIN } _, url, err := utils.GetUpdVerAndUrl(config["auto_update_url"]) //fmt.Println("url", url) if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } if len(url) > 0 { f, _ := os.OpenFile(*utils.Dir+"/auto_update", os.O_WRONLY|os.O_CREATE, 0600) f.WriteString(utils.Int64ToStr(utils.Time())) f.Close() err = utils.DcoinUpd(url) 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) }
func (p *Parser) SendDcFront() error { err := p.generalCheck() if err != nil { return p.ErrInfo(err) } verifyData := map[string]string{"from_user_id": "bigint", "to_user_id": "bigint", "currency_id": "bigint", "amount": "amount", "commission": "amount", "comment": "comment"} err = p.CheckInputData(verifyData) if err != nil { return p.ErrInfo(err) } if p.TxMaps.Float64["amount"] < 0.01 { // 0.01 - минимальная сумма return p.ErrInfo("amount") } // проверим, существует ли такая валюта в таблиуе DC-валют checkCurrency, err := p.CheckCurrency(p.TxMaps.Int64["currency_id"]) if !checkCurrency { // если нет, то проверяем список CF-валют checkCurrency, err := p.CheckCurrencyCF(p.TxMaps.Int64["currency_id"]) if err != nil { return p.ErrInfo(err) } if !checkCurrency { return p.ErrInfo("currency_id") } } nodeCommission, err := p.getMyNodeCommission(p.TxMaps.Int64["currency_id"], p.TxUserID, p.TxMaps.Float64["amount"]) if err != nil { return p.ErrInfo(err) } // проверим, удовлетворяет ли нас комиссия, которую предлагает юзер if p.TxMaps.Float64["commission"] < nodeCommission { return p.ErrInfo(fmt.Sprintf("commission %v<%v", p.TxMaps.Float64["commission"], nodeCommission)) } if p.BlockData != nil && p.BlockData.BlockId <= consts.ARBITRATION_BLOCK_START { for i := 0; i < 5; i++ { p.TxMaps.Float64["arbitrator"+utils.IntToStr(i)+"_commission"] = 0 // для check_sender_money } forSign := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s", p.TxMap["type"], p.TxMap["time"], p.TxMap["user_id"], p.TxMap["to_user_id"], p.TxMap["amount"], p.TxMap["commission"], utils.BinToHex(p.TxMap["comment"]), p.TxMap["currency_id"]) CheckSignResult, err := utils.CheckSign(p.PublicKeys, forSign, p.TxMap["sign"], false) if err != nil { return p.ErrInfo(err) } if !CheckSignResult { return p.ErrInfo("incorrect sign") } } else { dupArray := make(map[int64]int64) for i := 0; i < 5; i++ { arbitrator__commission := "arbitrator" + utils.IntToStr(i) + "_commission" arbitrator_ := "arbitrator" + utils.IntToStr(i) if !utils.CheckInputData(p.TxMap[arbitrator__commission], "amount") { return p.ErrInfo("arbitrator_commission") } if !utils.CheckInputData(p.TxMap[arbitrator_], "bigint") { return p.ErrInfo("arbitrator") } // если указал ID арбитра, то должна быть комиссия для него if p.TxMaps.Int64[arbitrator_] > 0 && p.TxMaps.Float64[arbitrator__commission] < 0.01 { return p.ErrInfo("arbitrator_commission") } // на всяк случай не даем арбитрам возможность быть арбитрами самим себе if p.TxMaps.Int64[arbitrator_] == p.TxUserID { return p.ErrInfo("arbitrator = user_id") } if p.TxMaps.Int64[arbitrator_] > 0 { dupArray[utils.BytesToInt64(p.TxMap[arbitrator_])]++ if dupArray[utils.BytesToInt64(p.TxMap[arbitrator_])] > 1 { return p.ErrInfo("doubles") } } if p.TxMaps.Int64[arbitrator_] > 0 { arbitrator := p.TxMap[arbitrator_] // проверим, является ли арбитром указанный user_id arbitratorConditionsJson, err := p.Single("SELECT conditions FROM arbitrator_conditions WHERE user_id = ?", utils.BytesToInt64(arbitrator)).Bytes() if err != nil { return p.ErrInfo(err) } arbitratorConditionsMap := make(map[string][5]string) err = json.Unmarshal(arbitratorConditionsJson, &arbitratorConditionsMap) // арбитр к этому моменту мог передумать и убрать свои условия, уйдя из арбитров для новых сделок поставив [0] что вызовет тут ошибку if err != nil { log.Debug("arbitratorConditionsJson", arbitratorConditionsJson) return p.ErrInfo(err) } // проверим, работает ли выбранный арбитр с валютой данной сделки var checkCurrency int64 if p.TxMaps.Int64["currency_id"] > 1000 { checkCurrency = 1000 } else { checkCurrency = p.TxMaps.Int64["currency_id"] } if len(arbitratorConditionsMap[utils.Int64ToStr(checkCurrency)]) == 0 { return p.ErrInfo("len(arbitratorConditionsMap[checkCurrency]) == 0") } // указан ли этот арбитр в списке доверенных у продавца sellerArbitrator, err := p.Single("SELECT user_id FROM arbitration_trust_list WHERE user_id = ? AND arbitrator_user_id = ?", p.TxMaps.Int64["to_user_id"], utils.BytesToInt64(arbitrator)).Int64() if err != nil { return p.ErrInfo(err) } if sellerArbitrator == 0 { return p.ErrInfo("sellerArbitrator == 0") } // указан ли этот арбитр в списке доверенных у покупателя buyerArbitrator, err := p.Single("SELECT user_id FROM arbitration_trust_list WHERE user_id = ? AND arbitrator_user_id = ?", p.TxMaps.Int64["from_user_id"], utils.BytesToInt64(arbitrator)).Int64() if err != nil { return p.ErrInfo(err) } if buyerArbitrator == 0 { return p.ErrInfo("buyerArbitrator == 0") } // согласен ли продавец на манибек arbitrationDaysRefund, err := p.Single("SELECT arbitration_days_refund FROM users WHERE user_id = ?", p.TxMaps.Int64["to_user_id"]).Int64() if err != nil { return p.ErrInfo(err) } if arbitrationDaysRefund == 0 { return p.ErrInfo("buyerArbitrator == 0") } // готов ли арбитр рассматривать такую сумму сделки currencyIdStr := utils.Int64ToStr(p.TxMaps.Int64["currency_id"]) if p.TxMaps.Float64["amount"] < utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][0]) || (p.TxMaps.Float64["amount"] > utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][1]) && utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][1]) > 0) { return p.ErrInfo("amount") } // мин. комиссия, на которую согласен арбитр minArbitratorCommission := utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][4]) / 100 * p.TxMaps.Float64["amount"] if minArbitratorCommission > utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) && utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) > 0 { minArbitratorCommission = utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][3]) } if minArbitratorCommission < utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][2]) { minArbitratorCommission = utils.StrToFloat64(arbitratorConditionsMap[currencyIdStr][2]) } if utils.BytesToFloat64(p.TxMap[arbitrator__commission]) < minArbitratorCommission { return p.ErrInfo(" < minArbitratorCommission") } } } forSign := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", p.TxMap["type"], p.TxMap["time"], p.TxMap["user_id"], p.TxMap["to_user_id"], p.TxMap["amount"], p.TxMap["commission"], p.TxMap["arbitrator0"], p.TxMap["arbitrator1"], p.TxMap["arbitrator2"], p.TxMap["arbitrator3"], p.TxMap["arbitrator4"], p.TxMap["arbitrator0_commission"], p.TxMap["arbitrator1_commission"], p.TxMap["arbitrator2_commission"], p.TxMap["arbitrator3_commission"], p.TxMap["arbitrator4_commission"], utils.BinToHex(p.TxMap["comment"]), p.TxMap["currency_id"]) CheckSignResult, err := utils.CheckSign(p.PublicKeys, forSign, p.TxMap["sign"], false) if err != nil { return p.ErrInfo(err) } if !CheckSignResult { return p.ErrInfo("incorrect sign") } } /* wallets_buffer сделан не для защиты от двойной траты, а для того, чтобы нода, которая генерит блок не записала двойное списание в свой блок, который будет отправлен другим нодам и будет ими отвергнут. Для тр-ий типа new_forex_order используется простой запрет на запись в блок тр-ии new_forex_order+new_forex_order или new_forex_order+send_dc и пр. защита от двойного списания на основе даннных из блока, полученного из сети заключается в постепенной обработке тр-ий путем проверки front_ и занесения данных в БД (ParseDataFull). */ amountAndCommission, err := p.checkSenderMoney(p.TxMaps.Int64["currency_id"], p.TxMaps.Int64["from_user_id"], p.TxMaps.Float64["amount"], p.TxMaps.Float64["commission"], p.TxMaps.Float64["arbitrator0_commission"], p.TxMaps.Float64["arbitrator1_commission"], p.TxMaps.Float64["arbitrator2_commission"], p.TxMaps.Float64["arbitrator3_commission"], p.TxMaps.Float64["arbitrator4_commission"]) if err != nil { return p.ErrInfo(err) } // существует ли юзер-получатель err = p.CheckUser(p.TxMaps.Int64["to_user_id"]) if err != nil { return p.ErrInfo(err) } err = p.checkSpamMoney(p.TxMaps.Int64["currency_id"], p.TxMaps.Float64["amount"]) if err != nil { return p.ErrInfo(err) } // вычитаем из wallets_buffer // amount_and_commission взято из check_sender_money() err = p.updateWalletsBuffer(amountAndCommission, p.TxMaps.Int64["currency_id"]) if err != nil { return p.ErrInfo(err) } return nil }
/* * просто шлем всем, кто есть в nodes_connection хэши блока и тр-ий * если мы не майнер, то шлем всю тр-ию целиком, блоки слать не можем * если майнер - то шлем только хэши, т.к. у нас есть хост, откуда всё можно скачать * */ func Disseminator(chBreaker chan bool, chAnswer chan string) { defer func() { if r := recover(); r != nil { log.Error("daemon Recovered", r) panic(r) } }() const GoroutineName = "Disseminator" 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 = 300 } else { d.sleepTime = 1 } 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 } var hosts []map[string]string var nodeData map[string]string nodeConfig, err := d.GetNodeConfig() if len(nodeConfig["local_gate_ip"]) == 0 { // обычный режим hosts, err = d.GetAll(` SELECT miners_data.user_id, miners_data.tcp_host as host, node_public_key FROM nodes_connection LEFT JOIN miners_data ON nodes_connection.user_id = miners_data.user_id `, -1) if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue } if len(hosts) == 0 { if d.dSleep(d.sleepTime) { break BEGIN } log.Debug("len(hosts) == 0") continue } } else { // защищенный режим nodeData, err = d.OneRow("SELECT node_public_key, tcp_host FROM miners_data WHERE user_id = ?", nodeConfig["static_node_user_id"]).String() if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue } hosts = append(hosts, map[string]string{"host": nodeConfig["local_gate_ip"], "node_public_key": nodeData["node_public_key"], "user_id": nodeConfig["static_node_user_id"]}) } myUsersIds, err := d.GetMyUsersIds(false, false) if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue } myMinersIds, err := d.GetMyMinersIds(myUsersIds) if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue } log.Debug("%v", myUsersIds) log.Debug("%v", myMinersIds) // если среди тр-ий есть смена нодовского ключа, то слать через отправку хэшей с последющей отдачей данных может не получиться // т.к. при некорректном нодовском ключе придет зашифрованый запрос на отдачу данных, а мы его не сможем расшифровать т.к. ключ у нас неверный var changeNodeKey int64 if len(myUsersIds) > 0 { changeNodeKey, err = d.Single(` SELECT count(*) FROM transactions WHERE type = ? AND user_id IN (`+strings.Join(utils.SliceInt64ToString(myUsersIds), ",")+`) `, utils.TypeInt("ChangeNodeKey")).Int64() if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } } var dataType int64 // это тип для того, чтобы принимающая сторона могла понять, как именно надо обрабатывать присланные данные // если я майнер и работаю в обычном режиме, то должен слать хэши if len(myMinersIds) > 0 && len(nodeConfig["local_gate_ip"]) == 0 && changeNodeKey == 0 { log.Debug("0") dataType = 1 // определим, от кого будем слать r := utils.RandInt(0, len(myMinersIds)) myMinerId := myMinersIds[r] myUserId, err := d.Single("SELECT user_id FROM miners_data WHERE miner_id = ?", myMinerId).Int64() if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } // возьмем хэш текущего блока и номер блока // для теста ролбеков отключим на время data, err := d.OneRow("SELECT block_id, hash, head_hash FROM info_block WHERE sent = 0").Bytes() if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } err = d.ExecSql("UPDATE info_block SET sent = 1") if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } /* * Составляем данные на отправку * */ // 5 байт = наш user_id. Но они будут не первые, т.к. m_curl допишет вперед user_id получателя (нужно для пулов) toBeSent := utils.DecToBin(myUserId, 5) if len(data) > 0 { // блок // если 5-й байт = 0, то на приемнике будем читать блок, если = 1 , то сразу хэши тр-ий toBeSent = append(toBeSent, utils.DecToBin(0, 1)...) toBeSent = append(toBeSent, utils.DecToBin(utils.BytesToInt64(data["block_id"]), 3)...) toBeSent = append(toBeSent, data["hash"]...) toBeSent = append(toBeSent, data["head_hash"]...) err = d.ExecSql("UPDATE info_block SET sent = 1") if err != nil { if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } } else { // тр-ии без блока toBeSent = append(toBeSent, utils.DecToBin(1, 1)...) } // возьмем хэши тр-ий //utils.WriteSelectiveLog("SELECT hash, high_rate FROM transactions WHERE sent = 0 AND for_self_use = 0") transactions, err := d.GetAll("SELECT hash, high_rate FROM transactions WHERE sent = 0 AND for_self_use = 0", -1) if err != nil { utils.WriteSelectiveLog(err) if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } // нет ни транзакций, ни блока для отправки... if len(transactions) == 0 && len(toBeSent) < 10 { //utils.WriteSelectiveLog("len(transactions) == 0") //log.Debug("len(transactions) == 0") if d.dSleep(d.sleepTime) { break BEGIN } log.Debug("len(transactions) == 0 && len(toBeSent) == 0") continue BEGIN } for _, data := range transactions { hexHash := utils.BinToHex([]byte(data["hash"])) toBeSent = append(toBeSent, utils.DecToBin(utils.StrToInt64(data["high_rate"]), 1)...) toBeSent = append(toBeSent, []byte(data["hash"])...) utils.WriteSelectiveLog("UPDATE transactions SET sent = 1 WHERE hex(hash) = " + string(hexHash)) affect, err := d.ExecSqlGetAffect("UPDATE transactions SET sent = 1 WHERE hex(hash) = ?", hexHash) if err != nil { utils.WriteSelectiveLog(err) if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } utils.WriteSelectiveLog("affect: " + utils.Int64ToStr(affect)) } // отправляем блок и хэши тр-ий, если есть что отправлять if len(toBeSent) > 0 { for _, host := range hosts { go d.DisseminatorType1(host["host"], utils.StrToInt64(host["user_id"]), host["node_public_key"], toBeSent, dataType) } } } else { log.Debug("1") var remoteNodeHost string // если просто юзер или работаю в защищенном режиме, то шлю тр-ии целиком. слать блоки не имею права. if len(nodeConfig["local_gate_ip"]) > 0 { dataType = 3 remoteNodeHost = nodeData["host"] } else { dataType = 2 remoteNodeHost = "" } log.Debug("dataType: %d", dataType) var toBeSent []byte // сюда пишем все тр-ии, которые будем слать другим нодам // возьмем хэши и сами тр-ии utils.WriteSelectiveLog("SELECT hash, data FROM transactions WHERE sent = 0") rows, err := d.Query("SELECT hash, data FROM transactions WHERE sent = 0") if err != nil { utils.WriteSelectiveLog(err) if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } for rows.Next() { var hash, data []byte err = rows.Scan(&hash, &data) if err != nil { rows.Close() if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } log.Debug("hash %x", hash) hashHex := utils.BinToHex(hash) utils.WriteSelectiveLog("UPDATE transactions SET sent = 1 WHERE hex(hash) = " + string(hashHex)) affect, err := d.ExecSqlGetAffect("UPDATE transactions SET sent = 1 WHERE hex(hash) = ?", hashHex) if err != nil { utils.WriteSelectiveLog(err) rows.Close() if d.dPrintSleep(err, d.sleepTime) { break BEGIN } continue BEGIN } utils.WriteSelectiveLog("affect: " + utils.Int64ToStr(affect)) toBeSent = append(toBeSent, data...) } rows.Close() // шлем тр-ии if len(toBeSent) > 0 { for _, host := range hosts { userId := utils.StrToInt64(host["user_id"]) go func(host string, userId int64, node_public_key string) { log.Debug("host %v / userId %v", host, userId) conn, err := utils.TcpConn(host) if err != nil { log.Error("%v", utils.ErrInfo(err)) return } defer conn.Close() randTestblockHash, err := d.Single("SELECT head_hash FROM queue_testblock").String() if err != nil { log.Error("%v", utils.ErrInfo(err)) return } // получаем IV + ключ + зашифрованный текст encryptedData, _, _, err := utils.EncryptData(toBeSent, []byte(node_public_key), randTestblockHash) if err != nil { log.Error("%v", utils.ErrInfo(err)) return } // вначале шлем тип данных, чтобы принимающая сторона могла понять, как именно надо обрабатывать присланные данные _, err = conn.Write(utils.DecToBin(dataType, 1)) if err != nil { log.Error("%v", utils.ErrInfo(err)) return } // т.к. на приеме может быть пул, то нужно дописать в начало user_id, чьим нодовским ключем шифруем /*_, err = conn.Write(utils.DecToBin(userId, 5)) if err != nil { log.Error("%v", utils.ErrInfo(err)) return }*/ encryptedData = append(utils.DecToBin(userId, 5), encryptedData...) // это может быть защищенное локальное соедниение (dataType = 3) и принимающему ноду нужно знать, куда дальше слать данные и чьим они зашифрованы ключем if len(remoteNodeHost) > 0 { /* _, err = conn.Write([]byte(remoteNodeHost)) if err != nil { log.Error("%v", utils.ErrInfo(err)) return }*/ encryptedData = append([]byte(remoteNodeHost), encryptedData...) } log.Debug("encryptedData %x", encryptedData) // в 4-х байтах пишем размер данных, которые пошлем далее size := utils.DecToBin(len(encryptedData), 4) _, err = conn.Write(size) if err != nil { log.Error("%v", utils.ErrInfo(err)) return } // далее шлем сами данные _, err = conn.Write(encryptedData) if err != nil { log.Error("%v", utils.ErrInfo(err)) return } }(host["host"], userId, host["node_public_key"]) } } } d.dbUnlock() if d.dSleep(d.sleepTime) { break BEGIN } } log.Debug("break BEGIN %v", GoroutineName) }