本文整理汇总了Golang中github.com/c-darwin/dcoin-go/packages/dcparser.Parser类的典型用法代码示例。如果您正苦于以下问题:Golang Parser类的具体用法?Golang Parser怎么用?Golang Parser使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Parser类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
f := tests_utils.InitLog()
defer f.Close()
db := tests_utils.DbConn()
parser := new(dcparser.Parser)
parser.DCDB = db
err := parser.RollbackToBlockId(261950)
if err != nil {
fmt.Println(err)
}
}
示例2: BlockExplorer
func (c *Controller) BlockExplorer() (string, error) {
var err error
blockId := int64(utils.StrToFloat64(c.Parameters["blockId"]))
start := int64(utils.StrToFloat64(c.Parameters["start"]))
var data, sql string
if start > 0 || (start == 0 && blockId == 0) {
if start == 0 && blockId == 0 {
data += "<h3>Latest Blocks</h3>"
sql = ` SELECT data, hash
FROM block_chain
ORDER BY id DESC
LIMIT 15`
} else {
sql = ` SELECT data, hash
FROM block_chain
ORDER BY id ASC
LIMIT ` + utils.Int64ToStr(start-1) + `, 100`
}
data += `<table class="table"><tr><th>Block</th><th>Hash</th><th>Time</th><th><nobr>User id</nobr></th><th><nobr>Miner id</nobr></th><th>Level</th><th>Transactions</th></tr>`
blocksChain, err := c.GetAll(sql, -1)
if err != nil {
return "", utils.ErrInfo(err)
}
for _, blockData := range blocksChain {
hash := utils.BinToHex([]byte(blockData["hash"]))
binaryData := []byte(blockData["data"])
parser := new(dcparser.Parser)
parser.DCDB = c.DCDB
parser.BinaryData = binaryData
err = parser.ParseDataLite()
parser.BlockData.Sign = utils.BinToHex(parser.BlockData.Sign)
minerId, err := c.GetMinerId(parser.BlockData.UserId)
if err != nil {
return "", utils.ErrInfo(err)
}
data += fmt.Sprintf(`<tr><td><a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">%d</a></td><td>%s</td><td><nobr><span class='unixtime'>%d</span></nobr></td><td>%d</td><td>%d</td><td>%d</td><td>`, parser.BlockData.BlockId, parser.BlockData.BlockId, hash, parser.BlockData.Time, parser.BlockData.UserId, minerId, parser.BlockData.Level)
data += utils.IntToStr(len(parser.TxMapArr))
data += "</td></tr>"
}
data += "</table>"
} else if blockId > 0 {
data += `<table class="table">`
blockChain, err := c.OneRow("SELECT data, hash, cur_0l_miner_id, max_miner_id FROM block_chain WHERE id = ?", blockId).String()
if err != nil {
return "", utils.ErrInfo(err)
}
binToHexArray := []string{"sign", "public_key", "encrypted_message", "comment", "bin_public_keys"}
hash := utils.BinToHex([]byte(blockChain["hash"]))
binaryData := blockChain["data"]
parser := new(dcparser.Parser)
parser.DCDB = c.DCDB
parser.BinaryData = []byte(binaryData)
err = parser.ParseDataLite()
if err != nil {
return "", utils.ErrInfo(err)
}
parser.BlockData.Sign = utils.BinToHex(parser.BlockData.Sign)
previous := parser.BlockData.BlockId - 1
next := parser.BlockData.BlockId + 1
levelsRange := utils.GetBlockGeneratorMinerIdRange(utils.StrToInt64(blockChain["cur_0l_miner_id"]), utils.StrToInt64(blockChain["max_miner_id"]))
minerId, err := c.GetMinerId(parser.BlockData.UserId)
if err != nil {
return "", utils.ErrInfo(err)
}
_, _, _, CurrentUserId, _, _, _ := c.TestBlock()
maxMinerId, err := c.Single("SELECT max(miner_id) FROM miners").Int64()
if err != nil {
return "", utils.ErrInfo(err)
}
currentMinerId, err := c.Single("SELECT miner_id FROM miners_data WHERE user_id = ?", CurrentUserId).Int64()
if err != nil {
return "", utils.ErrInfo(err)
}
NextBlockLevelsRange := utils.GetBlockGeneratorMinerIdRange(currentMinerId, maxMinerId)
data += fmt.Sprintf(`<tr><td><strong>Raw data</strong></td><td><a href='ajax?controllerName=getBlock&id=%d&download=1' target='_blank'>Download</a></td></tr>`, parser.BlockData.BlockId)
data += fmt.Sprintf(`<tr><td><strong>Block_id</strong></td><td>%d (<a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">Previous</a> / <a href="#" onclick="dc_navigate('blockExplorer', {'blockId':%d})">Next</a> )</td></tr>`, parser.BlockData.BlockId, previous, next)
data += fmt.Sprintf(`<tr><td><strong>Hash</strong></td><td>%s</td></tr>`, hash)
data += fmt.Sprintf(`<tr><td><strong>Time</strong></td><td><span class='unixtime'>%d</span> / %d</td></tr>`, parser.BlockData.Time, parser.BlockData.Time)
data += fmt.Sprintf(`<tr><td><strong>User_id</strong></td><td>%d</td></tr>`, parser.BlockData.UserId)
data += fmt.Sprintf(`<tr><td><strong>Miner_Id</strong></td><td>%d</td></tr>`, minerId)
data += fmt.Sprintf(`<tr><td><strong>Level</strong></td><td>%d (%v) next: %v</td></tr>`, parser.BlockData.Level, levelsRange, NextBlockLevelsRange)
data += fmt.Sprintf(`<tr><td><strong>Sign</strong></td><td>%s</td></tr>`, parser.BlockData.Sign)
if len(parser.TxMapArr) > 0 {
data += `<tr><td><strong>Transactions</strong></td><td><div><pre style='width: 700px'>`
for i := 0; i < len(parser.TxMapArr); i++ {
for k, data_ := range parser.TxMapArr[i] {
if utils.InSliceString(k, binToHexArray) {
parser.TxMapArr[i][k] = utils.BinToHex(data_)
}
if k == "file" {
parser.TxMapArr[i][k] = []byte("file size: " + utils.IntToStr(len(data_)))
} else if k == "code" {
parser.TxMapArr[i][k] = utils.DSha256(data_)
} else if k == "secret" {
parser.TxMapArr[i][k] = utils.BinToHex(data_)
//.........这里部分代码省略.........
示例3: ElectionsAdmin
//.........这里部分代码省略.........
// проверим, прошло ли 2 недели с момента последнего обновления
adminTime, err := d.Single("SELECT time FROM admin").Int64()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
if curTime-adminTime <= variables.Int64["new_pct_period"] {
if d.unlockPrintSleep(utils.ErrInfo("14 day error"), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
// сколько всего майнеров
countMiners, err := d.Single("SELECT count(miner_id) FROM miners WHERE active = 1").Int64()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
if countMiners < 1000 {
if d.unlockPrintSleep(utils.ErrInfo("countMiners < 1000"), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
// берем все голоса
var newAdmin int64
votes_admin, err := d.GetMap(`
SELECT admin_user_id,
count(user_id) as votes
FROM votes_admin
WHERE time > ?
GROUP BY admin_user_id
`, "admin_user_id", "votes", curTime-variables.Int64["new_pct_period"])
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
for admin_user_id, votes := range votes_admin {
// если более 50% майнеров проголосовали
if utils.StrToInt64(votes) > countMiners/2 {
newAdmin = utils.StrToInt64(admin_user_id)
}
}
if newAdmin == 0 {
if d.unlockPrintSleep(utils.ErrInfo("newAdmin == 0"), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
_, myUserId, _, _, _, _, err := d.TestBlock()
forSign := fmt.Sprintf("%v,%v,%v,%v", utils.TypeInt("NewAdmin"), curTime, myUserId, newAdmin)
binSign, err := d.GetBinSign(forSign, myUserId)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
data := utils.DecToBin(utils.TypeInt("NewAdmin"), 1)
data = append(data, utils.DecToBin(curTime, 4)...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(myUserId))...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(newAdmin))...)
data = append(data, utils.EncodeLengthPlusData([]byte(binSign))...)
err = d.InsertReplaceTxInQueue(data)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
p := new(dcparser.Parser)
p.DCDB = d.DCDB
err = p.TxParser(utils.HexToBin(utils.Md5(data)), data, true)
if err != nil {
if d.unlockPrintSleep(err, d.sleepTime) {
break BEGIN
}
continue BEGIN
}
d.dbUnlock()
if d.dSleep(d.sleepTime) {
break BEGIN
}
}
log.Debug("break BEGIN %v", GoroutineName)
}
示例4: Start
//.........这里部分代码省略.........
log.Error("%v", utils.ErrInfo(err))
}
}
if utils.VersionOrdinal(pidMap["version"]) < utils.VersionOrdinal("2.0.1b2") {
log.Debug("%v", "ALTER TABLE config ADD COLUMN sqlite_db_url varchar(255)")
err = utils.DB.ExecSql(`ALTER TABLE config ADD COLUMN sqlite_db_url varchar(255)`)
if err != nil {
log.Error("%v", utils.ErrInfo(err))
}
}
}
err = utils.DB.Close()
if err != nil {
log.Error("%v", utils.ErrInfo(err))
}
fmt.Println("DB Closed")
err = os.Remove(*utils.Dir + "/dcoin.pid")
if err != nil {
log.Error("%v", utils.ErrInfo(err))
}
log.Debug("dc.tmp %v", *utils.Dir+`/dc.tmp`)
err = exec.Command(*utils.OldFileName, "-dir", *utils.Dir).Start()
if err != nil {
log.Debug("%v", os.Stderr)
log.Debug("%v", utils.ErrInfo(err))
}
log.Debug("OldFileName %v", *utils.OldFileName)
os.Exit(1)
}
// откат БД до указанного блока
if *utils.RollbackToBlockId > 0 {
utils.DB, err = utils.NewDbConnect(configIni)
parser := new(dcparser.Parser)
parser.DCDB = utils.DB
err = parser.RollbackToBlockId(*utils.RollbackToBlockId)
if err != nil {
fmt.Println(err)
panic(err)
}
fmt.Print("complete")
os.Exit(0)
}
log.Debug("public")
IosLog("public")
if _, err := os.Stat(*utils.Dir + "/public"); os.IsNotExist(err) {
err = os.Mkdir(*utils.Dir+"/public", 0755)
if err != nil {
log.Error("%v", utils.ErrInfo(err))
panic(err)
os.Exit(1)
}
}
log.Debug("daemonsStart")
IosLog("daemonsStart")
daemons.StartDaemons()
IosLog("MonitorDaemons")
// мониторинг демонов
daemonsTable := make(map[string]string)
go func() {
for {
daemonNameAndTime := <-daemons.MonitorDaemonCh
示例5: QueueParserBlocks
func QueueParserBlocks(chBreaker chan bool, chAnswer chan string) {
defer func() {
if r := recover(); r != nil {
log.Error("daemon Recovered", r)
panic(r)
}
}()
const GoroutineName = "QueueParserBlocks"
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 = 10
}
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
}
prevBlockData, err := d.OneRow("SELECT * FROM info_block").String()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
newBlockData, err := d.OneRow("SELECT * FROM queue_blocks").String()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
if len(newBlockData) == 0 {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
newBlockData["head_hash_hex"] = string(utils.BinToHex(newBlockData["head_hash"]))
prevBlockData["head_hash_hex"] = string(utils.BinToHex(prevBlockData["head_hash"]))
newBlockData["hash_hex"] = string(utils.BinToHex(newBlockData["hash"]))
prevBlockData["hash_hex"] = string(utils.BinToHex(prevBlockData["hash"]))
variables, err := d.GetAllVariables()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
/*
* Базовая проверка
*/
// проверим, укладывается ли блок в лимит rollback_blocks_1
if utils.StrToInt64(newBlockData["block_id"]) > utils.StrToInt64(prevBlockData["block_id"])+variables.Int64["rollback_blocks_1"] {
d.DeleteQueueBlock(newBlockData["head_hash_hex"], newBlockData["hash_hex"])
if d.unlockPrintSleep(utils.ErrInfo("rollback_blocks_1"), 1) {
break BEGIN
}
continue BEGIN
}
// проверим не старый ли блок в очереди
if utils.StrToInt64(newBlockData["block_id"]) < utils.StrToInt64(prevBlockData["block_id"]) {
d.DeleteQueueBlock(newBlockData["head_hash_hex"], newBlockData["hash_hex"])
//.........这里部分代码省略.........
示例6: ReductionGenerator
//.........这里部分代码省略.........
}
continue BEGIN
}
log.Debug("sumPromisedAmount", sumPromisedAmount)
if len(sumWallets) > 0 {
for currencyId, sumAmount := range sumWallets {
//недопустимо для WOC
if currencyId == 1 {
continue
}
reductionTime, err := d.Single("SELECT max(time) FROM reduction WHERE currency_id = ? AND type = 'auto'", currencyId).Int64()
if err != nil {
if d.dPrintSleep(err, d.sleepTime) {
break BEGIN
}
continue BEGIN
}
log.Debug("reductionTime", reductionTime)
// прошло ли 48 часов
if curTime-reductionTime <= consts.AUTO_REDUCTION_PERIOD {
log.Debug("curTime-reductionTime <= consts.AUTO_REDUCTION_PERIOD %d <= %d", curTime-reductionTime, consts.AUTO_REDUCTION_PERIOD)
continue
}
// если обещанных сумм менее чем 100% от объема DC на кошельках, то запускаем урезание
log.Debug("utils.StrToFloat64(sumPromisedAmount[utils.IntToStr(currencyId)]) < sumAmount*consts.AUTO_REDUCTION_PROMISED_AMOUNT_PCT %d < %d", utils.StrToFloat64(sumPromisedAmount[utils.IntToStr(currencyId)]), sumAmount*consts.AUTO_REDUCTION_PROMISED_AMOUNT_PCT)
if utils.StrToFloat64(sumPromisedAmount[utils.IntToStr(currencyId)]) < sumAmount*consts.AUTO_REDUCTION_PROMISED_AMOUNT_PCT {
// проверим, есть ли хотя бы 1000 юзеров, у которых на кошелках есть или была данная валюты
countUsers, err := d.Single("SELECT count(user_id) FROM wallets WHERE currency_id = ?", currencyId).Int64()
if err != nil {
if d.dPrintSleep(err, d.sleepTime) {
break BEGIN
}
continue BEGIN
}
log.Debug("countUsers>=countUsers %d >= %d", countUsers, consts.AUTO_REDUCTION_PROMISED_AMOUNT_MIN)
if countUsers >= consts.AUTO_REDUCTION_PROMISED_AMOUNT_MIN {
reductionCurrencyId = currencyId
reductionPct = consts.AUTO_REDUCTION_PCT
reductionType = "promised_amount"
break
}
}
}
}
if reductionCurrencyId > 0 && reductionPct > 0 {
_, myUserId, _, _, _, _, err := d.TestBlock()
forSign := fmt.Sprintf("%v,%v,%v,%v,%v,%v", utils.TypeInt("NewReduction"), curTime, myUserId, reductionCurrencyId, reductionPct, reductionType)
log.Debug("forSign = %v", forSign)
binSign, err := d.GetBinSign(forSign, myUserId)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
data := utils.DecToBin(utils.TypeInt("NewReduction"), 1)
data = append(data, utils.DecToBin(curTime, 4)...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(myUserId))...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(int64(reductionCurrencyId)))...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(reductionPct))...)
data = append(data, utils.EncodeLengthPlusData([]byte(reductionType))...)
data = append(data, utils.EncodeLengthPlusData([]byte(binSign))...)
err = d.InsertReplaceTxInQueue(data)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
// и не закрывая main_lock переводим нашу тр-ию в verified=1, откатив все несовместимые тр-ии
// таким образом у нас будут в блоке только актуальные голоса.
// а если придет другой блок и станет verified=0, то эта тр-ия просто удалится.
p := new(dcparser.Parser)
p.DCDB = d.DCDB
err = p.TxParser(utils.HexToBin(utils.Md5(data)), data, true)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
}
d.dbUnlock()
if d.dSleep(d.sleepTime) {
break BEGIN
}
}
log.Debug("break BEGIN %v", GoroutineName)
}
示例7: TestblockIsReady
//.........这里部分代码省略.........
var testBlockDataTx []byte
transactionsTestBlock, err := d.GetList("SELECT data FROM transactions_testblock ORDER BY id ASC").String()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
for _, data := range transactionsTestBlock {
testBlockDataTx = append(testBlockDataTx, utils.EncodeLengthPlusData([]byte(data))...)
}
// в промежутке межде тем, как блок был сгенерирован и запуском данного скрипта может измениться текущий блок
// поэтому нужно проверять подпись блока из тестблока
prevBlockHash, err := d.Single("SELECT hash FROM info_block").Bytes()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
prevBlockHash = utils.BinToHex(prevBlockHash)
nodePublicKey, err := d.GetNodePublicKey(utils.StrToInt64(testBlockData["user_id"]))
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
forSign := fmt.Sprintf("0,%v,%s,%v,%v,%v,%s", testBlockData["block_id"], prevBlockHash, testBlockData["time"], testBlockData["user_id"], testBlockData["level"], utils.BinToHex([]byte(testBlockData["mrkl_root"])))
log.Debug("forSign %v", forSign)
log.Debug("signature %x", testBlockData["signature"])
p := new(dcparser.Parser)
p.DCDB = d.DCDB
// проверяем подпись
_, err = utils.CheckSign([][]byte{nodePublicKey}, forSign, []byte(testBlockData["signature"]), true)
if err != nil {
log.Error("incorrect signature %v")
p.RollbackTransactionsTestblock(true)
err = d.ExecSql("DELETE FROM testblock")
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
// БАГ
if utils.StrToInt64(testBlockData["block_id"]) == prevBlock.BlockId {
log.Error("testBlockData block_id = prevBlock.BlockId (%v=%v)", testBlockData["block_id"], prevBlock.BlockId)
err = p.RollbackTransactionsTestblock(true)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
err = d.ExecSql("DELETE FROM testblock")
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
示例8: Exchange
//.........这里部分代码省略.........
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" {
// расшифруем коммент
示例9: MakeTest
func MakeTest(txSlice [][]byte, blockData *utils.BlockData, txType string, testType string) error {
db := DbConn()
parser := new(dcparser.Parser)
parser.DCDB = db
parser.TxSlice = txSlice
parser.BlockData = blockData
parser.TxHash = []byte("111111111111111")
parser.Variables, _ = db.GetAllVariables()
// делаем снимок БД в виде хэшей до начала тестов
hashesStart, err := AllHashes(db)
if err != nil {
return err
}
//fmt.Println("dcparser."+txType+"Init")
err0 := utils.CallMethod(parser, txType+"Init")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
if testType == "work_and_rollback" {
err0 = utils.CallMethod(parser, txType)
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
//fmt.Println("-------------------")
// узнаем, какие таблицы были затронуты в результате выполнения основного метода
hashesMiddle, err := AllHashes(db)
if err != nil {
return utils.ErrInfo(err)
}
var tables []string
//fmt.Println("hashesMiddle", hashesMiddle)
//fmt.Println("hashesStart", hashesStart)
for table, hash := range hashesMiddle {
if hash != hashesStart[table] {
tables = append(tables, table)
}
}
fmt.Println("tables", tables)
// rollback
err0 := utils.CallMethod(parser, txType+"Rollback")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
// сраниим хэши, которые были до начала и те, что получились после роллбэка
hashesEnd, err := AllHashes(db)
if err != nil {
return utils.ErrInfo(err)
}
for table, hash := range hashesEnd {
if hash != hashesStart[table] {
fmt.Println("ERROR in table ", table)
}
}
} else if (len(os.Args) > 1 && os.Args[1] == "w") || testType == "work" {
err0 = utils.CallMethod(parser, txType)
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
} else if (len(os.Args) > 1 && os.Args[1] == "r") || testType == "rollback" {
err0 = utils.CallMethod(parser, txType+"Rollback")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
}
return nil
}
示例10: main
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.SetFlags(log.LstdFlags | log.Lshortfile)
txType := "NewPct"
txTime := "1426283713"
userId := []byte("1")
var txSlice [][]byte
// hash
txSlice = append(txSlice, []byte("22cb812e53e22ee539af4a1d39b4596d"))
// type
txSlice = append(txSlice, utils.Int64ToByte(TypeInt(txType)))
// time
txSlice = append(txSlice, []byte(txTime))
// user_id
txSlice = append(txSlice, userId)
//new_pct
txSlice = append(txSlice, []byte(`{"1":{"miner_pct":"0.0000000044318","user_pct":"0.0000000027036"},"72":{"miner_pct":"0.0000000047610","user_pct":"0.0000000029646"}}`))
// sign
txSlice = append(txSlice, []byte("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"))
blockData := new(utils.BlockData)
blockData.BlockId = 1200
blockData.Time = utils.StrToInt64(txTime)
blockData.UserId = 1
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)
parser := new(dcparser.Parser)
parser.DCDB = db
parser.TxSlice = txSlice
parser.BlockData = blockData
// делаем снимок БД в виде хэшей до начала тестов
hashesStart, err := parser.AllHashes()
err = dcparser.MakeTest(parser, txType, hashesStart)
if err != nil {
fmt.Println(err)
}
//go daemons.Testblock_is_ready()
//parser.Db.HashTableData("holidays", "", "")
//HashTableData(parser.Db.DB,"holidays", "", "")
//hashes, err := parser.Db.AllHashes()
utils.CheckErr(err)
//fmt.Println(hashes)
fmt.Println()
}
示例11: MakeFrontTest
func MakeFrontTest(transactionArray [][]byte, time int64, dataForSign string, txType string, userId int64, MY_PREFIX string, blockId int64) error {
db := DbConn()
priv, pub := genKeys()
nodeArr := []string{"new_admin", "votes_node_new_miner", "NewPct"}
var binSign []byte
if utils.InSliceString(txType, nodeArr) {
err := db.ExecSql("UPDATE my_node_keys SET private_key = ?", priv)
if err != nil {
return utils.ErrInfo(err)
}
err = db.ExecSql("UPDATE miners_data SET node_public_key = [hex] WHERE user_id = ?", pub, userId)
if err != nil {
return utils.ErrInfo(err)
}
k, err := db.GetNodePrivateKey(MY_PREFIX)
if err != nil {
return utils.ErrInfo(err)
}
fmt.Println("k", k)
privateKey, err := utils.MakePrivateKey(k)
if err != nil {
return utils.ErrInfo(err)
}
//fmt.Println("privateKey.PublicKey", privateKey.PublicKey)
//fmt.Println("privateKey.D", privateKey.D)
//fmt.Printf("privateKey.N %x\n", privateKey.N)
//fmt.Println("privateKey.Public", privateKey.Public())
binSign, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, utils.HashSha1(dataForSign))
//nodePublicKey, err := db.GetNodePublicKey(userId)
//fmt.Println("nodePublicKey", nodePublicKey)
//if err != nil {
// return utils.ErrInfo(err)
//}
//CheckSignResult, err := utils.CheckSign([][]byte{nodePublicKey}, dataForSign, binSign, true);
//fmt.Printf("binSign: %x\n", binSign)
//fmt.Println("err", err)
//fmt.Println("CheckSignResult", CheckSignResult)
} else {
err := db.ExecSql("UPDATE my_keys SET private_key = ?", priv)
if err != nil {
return utils.ErrInfo(err)
}
err = db.ExecSql("UPDATE users SET public_key_0 = [hex]", pub)
if err != nil {
return utils.ErrInfo(err)
}
k, err := db.GetPrivateKey(MY_PREFIX)
privateKey, err := utils.MakePrivateKey(k)
if err != nil {
return utils.ErrInfo(err)
}
binSign, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA1, utils.HashSha1(dataForSign))
binSign = utils.EncodeLengthPlusData(binSign)
}
//fmt.Println("HashSha1", utils.HashSha1(dataForSign))
//fmt.Printf("binSign %x\n", binSign)
//fmt.Println("dataForSign", dataForSign)
transactionArray = append(transactionArray, binSign)
parser := new(dcparser.Parser)
parser.DCDB = db
parser.GoroutineName = "test"
parser.TxSlice = transactionArray
parser.BlockData = &utils.BlockData{BlockId: blockId, Time: time, UserId: userId}
parser.TxHash = []byte("111111111111111")
parser.Variables, _ = parser.DCDB.GetAllVariables()
err0 := utils.CallMethod(parser, txType+"Init")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
err0 = utils.CallMethod(parser, txType+"Front")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
err0 = utils.CallMethod(parser, txType+"RollbackFront")
if i, ok := err0.(error); ok {
fmt.Println(err0.(error), i)
return err0.(error)
}
return nil
}
示例12: main
//.........这里部分代码省略.........
{101: "user"},
{295: "miner"},
}
test_data[18].holidays_array = [][]int64{
{0, 10},
{10, 20},
{30, 30},
{40, 50},
{66, 99},
{233, 1999},
}
test_data[18].max_promised_amount_array = []map[int64]string{
{0: "1000"},
{63: "3333"},
{156: "899"},
{220: "500"},
}
test_data[18].currency_id = 10
test_data[18].result = 5157.6623487708
test_data[19] = new(calcProfitTest)
test_data[19].amount = 1500
test_data[19].repaid_amount = 0
test_data[19].time_start = 50
test_data[19].time_finish = 140
test_data[19].pct_array = []map[int64]map[string]float64{
{0: {"user": 0.0059, "miner": 0.05}},
{36: {"user": 0.0088, "miner": 0.08}},
{164: {"user": 0.0049, "miner": 0.04}},
{223: {"user": 0.0029, "miner": 0.02}},
}
test_data[19].points_status_array = []map[int64]string{
{0: "miner"},
{98: "miner"},
{101: "user"},
{295: "miner"},
}
test_data[19].holidays_array = [][]int64{
{0, 10},
{10, 20},
{30, 30},
{40, 50},
{66, 99},
{233, 1999},
}
test_data[19].max_promised_amount_array = []map[int64]string{
{0: "1000"},
{63: "3333"},
{156: "899"},
{220: "500"},
}
test_data[19].currency_id = 1
test_data[19].result = 129106.50065867
test_data[20] = new(calcProfitTest)
test_data[20].amount = 1500
test_data[20].repaid_amount = 50
test_data[20].time_start = 50
test_data[20].time_finish = 140
test_data[20].pct_array = []map[int64]map[string]float64{
{0: {"user": 0.0059, "miner": 0.05}},
{36: {"user": 0.0088, "miner": 0.08}},
{164: {"user": 0.0049, "miner": 0.04}},
{223: {"user": 0.0029, "miner": 0.02}},
}
test_data[20].points_status_array = []map[int64]string{
{0: "miner"},
{98: "miner"},
{101: "user"},
{295: "miner"},
}
test_data[20].holidays_array = [][]int64{
{0, 10},
{10, 20},
{30, 30},
{40, 50},
{66, 99},
{233, 1999},
}
test_data[20].max_promised_amount_array = []map[int64]string{
{0: "1000"},
{63: "1525"},
{64: "1550"},
{139: "500"},
}
test_data[20].currency_id = 10
test_data[20].result = 4966.7977985526
f, _ := os.OpenFile("dclog.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0777)
defer f.Close()
// log.SetOutput(io.MultiWriter(f, os.Stdout))
log.SetOutput(f)
log.SetFlags(log.LstdFlags | log.Lshortfile)
for i := 0; i < 21; i++ {
p := new(dcparser.Parser)
profit, _ := p.CalcProfit_24946(test_data[i].amount, test_data[i].time_start, test_data[i].time_finish, test_data[i].pct_array, test_data[i].points_status_array, test_data[i].holidays_array, test_data[i].max_promised_amount_array, test_data[i].currency_id, test_data[i].repaid_amount)
//fmt.Println(i, utils.Round(test_data[i].result, 8), utils.Round(profit, 8))
}
}
示例13: QueueParserTestblock
func QueueParserTestblock(chBreaker chan bool, chAnswer chan string) {
defer func() {
if r := recover(); r != nil {
log.Error("daemon Recovered", r)
panic(r)
}
}()
const GoroutineName = "QueueParserTestblock"
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 = 1
}
if !d.CheckInstall(chBreaker, chAnswer, GoroutineName) {
return
}
d.DCDB = DbConnect(chBreaker, chAnswer, GoroutineName)
if d.DCDB == nil {
return
}
err = d.notMinerSetSleepTime(1800)
if err != nil {
log.Error("%v", err)
return
}
BEGIN:
for {
log.Info(GoroutineName)
MonitorDaemonCh <- []string{GoroutineName, utils.Int64ToStr(utils.Time())}
// проверим, не нужно ли нам выйти из цикла
if CheckDaemonsRestart(chBreaker, chAnswer, GoroutineName) {
break BEGIN
}
err, restart := d.dbLock()
if restart {
break BEGIN
}
if err != nil {
if d.dPrintSleep(err, d.sleepTime) {
break BEGIN
}
continue BEGIN
}
data, err := d.OneRow("SELECT * FROM queue_testblock ORDER BY head_hash ASC").String()
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue
}
if len(data) == 0 {
if d.unlockPrintSleepInfo(utils.ErrInfo(errors.New("len(data) == 0")), d.sleepTime) {
break BEGIN
}
continue
}
newBlock := []byte(data["data"])
newHeaderHash := utils.BinToHex([]byte(data["head_hash"]))
tx := utils.DeleteHeader(newBlock)
// сразу можно удалять данные из таблы-очереди
err = d.ExecSql("DELETE FROM queue_testblock WHERE hex(head_hash) = ?", newHeaderHash)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(errors.New("len(data) == 0")), d.sleepTime) {
break BEGIN
}
continue
}
// прежде всего нужно проверить, а нет ли в этом блоке ошибок с несовметимыми тр-ми
// при полной проверке, а не только фронтальной проблем с несовместимыми тр-ми не будет, т.к. там даные сразу пишутся в таблицы
// а тут у нас данные пишутся только в log_time_
// и сами тр-ии пишем в отдельную таблу
p := new(dcparser.Parser)
p.DCDB = d.DCDB
if len(tx) > 0 {
log.Debug("len(tx): %d", len(tx))
for {
log.Debug("tx: %x", tx)
txSize := utils.DecodeLength(&tx)
log.Debug("txSize: %d", txSize)
// отделим одну транзакцию от списка транзакций
txBinaryData := utils.BytesShift(&tx, txSize)
log.Debug("txBinaryData: %x", txBinaryData)
// проверим, нет ли несовместимых тр-ий
//.........这里部分代码省略.........
示例14: main
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.SetFlags(log.LstdFlags | log.Lshortfile)
dir, err := utils.GetCurrentDir()
if err != nil {
log.Fatal(err)
}
config, err := configparser.Read(dir + "/config.ini")
if err != nil {
log.Fatal(err)
}
configIni, err := config.Section("main")
txType := "NewHolidays"
txTime := "1426283713"
blockData := make(map[string]string)
var txSlice []string
// hash
txSlice = append(txSlice, "22cb812e53e22ee539af4a1d39b4596d")
// type
txSlice = append(txSlice, strconv.Itoa(int(TypeInt(txType))))
// time
txSlice = append(txSlice, txTime)
// user_id
txSlice = append(txSlice, strconv.FormatInt(1, 10))
//start
txSlice = append(txSlice, strconv.FormatInt(100000, 10))
//end
txSlice = append(txSlice, strconv.FormatInt(4545, 10))
// sign
txSlice = append(txSlice, "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
blockData["block_id"] = strconv.FormatInt(185510, 10)
blockData["time"] = txTime
blockData["user_id"] = strconv.FormatInt(1, 10)
//fmt.Println(txSlice)
parser := new(dcparser.Parser)
parser.DCDB = utils.NewDbConnect(configIni)
parser.TxSlice = txSlice
parser.BlockData = blockData
/*for i:=0; i<10000; i++ {
x := func() {
stmt, err := parser.DCDB.Prepare(`INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)`)
defer stmt.Close()
if err!=nil {
fmt.Println(err)
}
_, err = stmt.Exec(11111, "testblock_generator")
if err!=nil {
fmt.Println(err)
}
}
x()
//stmt, _ := parser.DCDB.Prepare(`INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)`)
//fmt.Println(err)
//defer stmt.Close()
//_, _ = stmt.Exec(11111, "testblock_generator")
//fmt.Println(err)
//_, _ = parser.DCDB.Query("INSERT INTO main_lock(lock_time,script_name) VALUES($1,$2)", 11111, "testblock_generator")
x2 := func() {
row, err := parser.DCDB.Query("DELETE FROM main_lock WHERE script_name='testblock_generator'")
defer row.Close()
if err!=nil {
fmt.Println(err)
}
}
x2()
//parser.DCDB.DbLock()
//parser.DCDB.DbUnlock()
//fmt.Println(i)
}*/
fmt.Println()
err = dcparser.MakeTest(parser, txType, hashesStart)
if err != nil {
fmt.Println("err", err)
}
//go daemons.Testblock_is_ready()
//parser.Db.HashTableData("holidays", "", "")
//HashTableData(parser.Db.DB,"holidays", "", "")
//hashes, err := parser.Db.AllHashes()
utils.CheckErr(err)
//fmt.Println(hashes)
fmt.Println()
/*
var ptr reflect.Value
var value reflect.Value
//var finalMethod reflect.Value
i := Test{Start: "start"}
//.........这里部分代码省略.........
示例15: PctGenerator
//.........这里部分代码省略.........
log.Info("%v", "maxUserPctY", maxUserPctY, "userMaxKey", userMaxKey, "currencyIdStr", currencyIdStr)
// отрезаем лишнее, т.к. поиск идет ровно до макимального возможного, т.е. до miner_pct/2
pctArr = utils.DelUserPct(pctArr, userMaxKey)
log.Info("%v", "pctArr", pctArr)
key = utils.GetMaxVote(pctArr, 0, userMaxKey, 100)
log.Info("%v", "data[user_pct]", data["user_pct"])
log.Info("%v", "pctArr", pctArr)
log.Info("%v", "userMaxKey", userMaxKey)
log.Info("%v", "key", key)
newPct["currency"][currencyIdStr]["user_pct"] = utils.GetPctValue(key)
log.Info("%v", "user_pct", newPct["currency"][currencyIdStr]["user_pct"])
}
newPct_ := new(newPctType)
newPct_.Currency = make(map[string]map[string]string)
newPct_.Currency = newPct["currency"]
newPct_.Referral = make(map[string]int64)
refLevels := []string{"first", "second", "third"}
for i := 0; i < len(refLevels); i++ {
level := refLevels[i]
var votesReferral []map[int64]int64
// берем все голоса
rows, err := d.Query("SELECT " + level + ", count(user_id) as votes FROM votes_referral GROUP BY " + level + " ORDER BY " + level + " ASC ")
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
for rows.Next() {
var level_, votes int64
err = rows.Scan(&level_, &votes)
if err != nil {
rows.Close()
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
votesReferral = append(votesReferral, map[int64]int64{level_: votes})
}
rows.Close()
newPct_.Referral[level] = (utils.GetMaxVote(votesReferral, 0, 30, 10))
}
jsonData, err := json.Marshal(newPct_)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
_, myUserId, _, _, _, _, err := d.TestBlock()
forSign := fmt.Sprintf("%v,%v,%v,%s", utils.TypeInt("NewPct"), curTime, myUserId, jsonData)
log.Debug("forSign = %v", forSign)
binSign, err := d.GetBinSign(forSign, myUserId)
log.Debug("binSign = %x", binSign)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
data := utils.DecToBin(utils.TypeInt("NewPct"), 1)
data = append(data, utils.DecToBin(curTime, 4)...)
data = append(data, utils.EncodeLengthPlusData(utils.Int64ToByte(myUserId))...)
data = append(data, utils.EncodeLengthPlusData(jsonData)...)
data = append(data, utils.EncodeLengthPlusData([]byte(binSign))...)
err = d.InsertReplaceTxInQueue(data)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
// и не закрывая main_lock переводим нашу тр-ию в verified=1, откатив все несовместимые тр-ии
// таким образом у нас будут в блоке только актуальные голоса.
// а если придет другой блок и станет verified=0, то эта тр-ия просто удалится.
p := new(dcparser.Parser)
p.DCDB = d.DCDB
err = p.TxParser(utils.HexToBin(utils.Md5(data)), data, true)
if err != nil {
if d.unlockPrintSleep(utils.ErrInfo(err), d.sleepTime) {
break BEGIN
}
continue BEGIN
}
}
d.dbUnlock()
if d.dSleep(d.sleepTime) {
break BEGIN
}
}
log.Debug("break BEGIN %v", GoroutineName)
}