From f9e0a32223db987c1a002d5c13cdcee74bc64568 Mon Sep 17 00:00:00 2001 From: powerpook Date: Wed, 15 Jul 2020 13:12:52 +0800 Subject: [PATCH] update --- .travis.yml | 1 - packages/api/history_test.go | 13 +- packages/daemons/subnode_agent_data.go | 16 +- packages/daemons/vde_src_task_from_sche.go | 8 + packages/daylight/windows.go | 25 +-- packages/language/language.go | 21 ++- packages/migration/obs/tables_data.go | 9 +- packages/migration/timezones.go | 17 +- packages/model/assign_get_info.go | 18 +-- packages/model/language.go | 9 +- packages/model/pages.go | 15 +- packages/model/querycost/explain.go | 14 +- packages/model/queue_tx.go | 20 ++- packages/model/responecode.go | 149 ++++++++++++++++++ packages/model/signatures.go | 12 +- packages/model/system_parameters.go | 12 +- packages/network/httpserver/max_body.go | 10 ++ packages/network/tcpserver/type2.go | 6 + packages/smart/math.go | 22 ++- packages/smart/queryBuilder/query_builder.go | 37 ++--- .../smart/queryBuilder/query_builder_test.go | 10 +- packages/smart/selective.go | 15 -- packages/transaction/custom/first_block.go | 16 +- packages/utils/metric/metrics.go | 17 +- packages/utils/tx/builder.go | 8 +- 25 files changed, 336 insertions(+), 164 deletions(-) create mode 100644 packages/model/responecode.go create mode 100644 packages/network/httpserver/max_body.go diff --git a/.travis.yml b/.travis.yml index 591a4c46..db75a625 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,3 @@ language: go env: GO111MODULE=on go: - - 1.12.x diff --git a/packages/api/history_test.go b/packages/api/history_test.go index cc007b53..de34f328 100644 --- a/packages/api/history_test.go +++ b/packages/api/history_test.go @@ -5,16 +5,15 @@ package api -import ( - stdErrors "errors" - "testing" -) - -func TestHistory(t *testing.T) { - if err := keyLogin(1); err != nil { + var ret historyResult + err := sendGet("history/pages/1", nil, &ret) + if err != nil { t.Error(err) return } + if len(ret.List) == 0 { + t.Error(stdErrors.New("History should not be empty")) + } err = sendGet("history/pages/1000", nil, &ret) if err != nil { diff --git a/packages/daemons/subnode_agent_data.go b/packages/daemons/subnode_agent_data.go index 062997ca..02dd99bc 100644 --- a/packages/daemons/subnode_agent_data.go +++ b/packages/daemons/subnode_agent_data.go @@ -64,6 +64,15 @@ func SubNodeAgentData(ctx context.Context, d *daemon) error { //} nodePrivateKey, err := utils.GetNodePrivateKey() + if err != nil || len(nodePrivateKey) < 1 { + if err == nil { + log.WithFields(log.Fields{"type": consts.EmptyObject}).Error("node private key is empty") + } + return err + } + + // send task data + for _, item := range ShareData { // dataBase64, err := base64.StdEncoding.DecodeString(string(item.Data)) if err != nil { @@ -108,13 +117,6 @@ func SubNodeAgentData(ctx context.Context, d *daemon) error { if err != nil { log.WithError(err) } - - // - //log_err = item.DataSendErr - ////Generate a chain request on the log - //log_type = 3 // - //if LogMode == 3 { //0 - // //fmt.Println("There is no need to generate a log") //} else if LogMode == 1 || LogMode == 2 { // if LogMode == 1 { //1 // chain_state = 5 diff --git a/packages/daemons/vde_src_task_from_sche.go b/packages/daemons/vde_src_task_from_sche.go index 0b4aa829..316b0818 100644 --- a/packages/daemons/vde_src_task_from_sche.go +++ b/packages/daemons/vde_src_task_from_sche.go @@ -1,3 +1,11 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) IBAX. All rights reserved. + "fmt" + "time" + + "github.com/IBAX-io/go-ibax/packages/model" + + log "github.com/sirupsen/logrus" ) //Scheduling task to run diff --git a/packages/daylight/windows.go b/packages/daylight/windows.go index d52d33ee..15d2ec2d 100644 --- a/packages/daylight/windows.go +++ b/packages/daylight/windows.go @@ -1,14 +1,4 @@ // +build windows - -/*--------------------------------------------------------------------------------------------- - * Copyright (c) IBAX. All rights reserved. - * See LICENSE in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -package daylight - -import ( - "fmt" "os/exec" "regexp" "time" @@ -16,6 +6,21 @@ import ( "github.com/IBAX-io/go-ibax/packages/consts" "github.com/IBAX-io/go-ibax/packages/model" + log "github.com/sirupsen/logrus" +) + +// KillPid kills the process with the specified pid +func KillPid(pid string) error { + if model.DBConn != nil { + sd := &model.StopDaemon{StopTime: time.Now().Unix()} + err := sd.Create() + if err != nil { + log.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("Error creating StopDaemon") + return err + } + } + rez, err := exec.Command("tasklist", "/fi", "PID eq "+pid).Output() + if err != nil { log.WithFields(log.Fields{"type": consts.CommandExecutionError, "err": err, "cmd": "tasklist /fi PID eq" + pid}).Error("Error executing command") return err } diff --git a/packages/language/language.go b/packages/language/language.go index 65d7a3a3..ac86679d 100644 --- a/packages/language/language.go +++ b/packages/language/language.go @@ -160,6 +160,16 @@ func LangText(transaction *model.DbTransaction, in string, state int, accept str return val, true } } + return (*lres)[lng], true + } + return in, false +} + +// LangMacro replaces all inclusions of $resname$ in the incoming text with the corresponding language resources, +// if they exist +func LangMacro(input string, state int, accept string) string { + if !strings.ContainsRune(input, '$') { + return input } syschar := '$' length := utf8.RuneCountInString(input) @@ -175,17 +185,6 @@ func LangText(transaction *model.DbTransaction, in string, state int, accept str if r != syschar { if isName { name = append(name, r) - if len(name) > 64 || r < ' ' { - clearname() - } - } else { - result = append(result, r) - } - continue - } - if isName { - value, ok := LangText(nil, string(name), state, accept) - if ok { result = append(result, []rune(value)...) isName = false } else { diff --git a/packages/migration/obs/tables_data.go b/packages/migration/obs/tables_data.go index 136d6a9d..7ae29460 100644 --- a/packages/migration/obs/tables_data.go +++ b/packages/migration/obs/tables_data.go @@ -162,12 +162,6 @@ var tablesDataSQL = `INSERT INTO "1_tables" ("id", "name", "permissions","column "new_column": "ContractConditions(\"MainCondition\")"}', '{"name": "ContractConditions(\"MainCondition\")", "value": "ContractConditions(\"MainCondition\")", - "conditions": "ContractConditions(\"MainCondition\")"}', - 'ContractAccess("@1EditTable")'), - ('17', 'app_params', - '{"insert": "ContractConditions(\"MainCondition\")", "update": "ContractConditions(\"MainCondition\")", - "new_column": "ContractConditions(\"MainCondition\")"}', - '{"app_id": "ContractConditions(\"MainCondition\")", "name": "ContractConditions(\"MainCondition\")", "value": "ContractConditions(\"MainCondition\")", "conditions": "ContractConditions(\"MainCondition\")"}', @@ -189,3 +183,6 @@ var tablesDataSQL = `INSERT INTO "1_tables" ("id", "name", "permissions","column "key": "false", "value": "true", "account": "false" + }', + 'ContractConditions("MainCondition")'); +` diff --git a/packages/migration/timezones.go b/packages/migration/timezones.go index e2defdf7..6b0edda9 100644 --- a/packages/migration/timezones.go +++ b/packages/migration/timezones.go @@ -220,13 +220,6 @@ INSERT INTO "1_time_zones" VALUES (next_id('1_time_zones'), 'Antarctica/Macquarie', '+11:00'), (next_id('1_time_zones'), 'Antarctica/Mawson', '+05:00'), (next_id('1_time_zones'), 'Antarctica/McMurdo', '+12:00'), -(next_id('1_time_zones'), 'Antarctica/Palmer', '-03:00'), -(next_id('1_time_zones'), 'Antarctica/Rothera', '-03:00'), -(next_id('1_time_zones'), 'Antarctica/Syowa', '+03:00'), -(next_id('1_time_zones'), 'Antarctica/Troll', '+02:00'), -(next_id('1_time_zones'), 'Antarctica/Vostok', '+06:00'), -(next_id('1_time_zones'), 'Arctic/Longyearbyen', '+02:00'), -(next_id('1_time_zones'), 'Asia/Aden', '+03:00'), (next_id('1_time_zones'), 'Asia/Almaty', '+06:00'), (next_id('1_time_zones'), 'Asia/Amman', '+03:00'), (next_id('1_time_zones'), 'Asia/Anadyr', '+12:00'), @@ -431,4 +424,14 @@ INSERT INTO "1_time_zones" VALUES (next_id('1_time_zones'), 'Pacific/Noumea', '+11:00'), (next_id('1_time_zones'), 'Pacific/Pago_Pago', '-11:00'), (next_id('1_time_zones'), 'Pacific/Palau', '+09:00'), +(next_id('1_time_zones'), 'Pacific/Pitcairn', '-08:00'), +(next_id('1_time_zones'), 'Pacific/Pohnpei', '+11:00'), +(next_id('1_time_zones'), 'Pacific/Port_Moresby', '+10:00'), +(next_id('1_time_zones'), 'Pacific/Rarotonga', '-10:00'), +(next_id('1_time_zones'), 'Pacific/Saipan', '+10:00'), +(next_id('1_time_zones'), 'Pacific/Tahiti', '-10:00'), +(next_id('1_time_zones'), 'Pacific/Tarawa', '+12:00'), +(next_id('1_time_zones'), 'Pacific/Tongatapu', '+13:00'), +(next_id('1_time_zones'), 'Pacific/Wake', '+12:00'), +(next_id('1_time_zones'), 'Pacific/Wallis', '+12:00'); ` diff --git a/packages/model/assign_get_info.go b/packages/model/assign_get_info.go index 2690c147..c6911c58 100644 --- a/packages/model/assign_get_info.go +++ b/packages/model/assign_get_info.go @@ -15,26 +15,16 @@ type AssignRules struct { TotalAmount string `json:"total_amount"` } -// AssignGetInfo is model -type AssignGetInfo struct { - ID int64 `gorm:"primary_key;not null"` - Type int64 `gorm:"not null"` - Keyid int64 `gorm:"not null"` - TotalAmount decimal.Decimal `gorm:"not null"` - BalanceAmount decimal.Decimal `gorm:"not null"` - Amount decimal.Decimal `gorm:"not null"` - Latestid int64 `gorm:"not null"` - Deleted int64 `gorm:"not null"` - DateUpdated int64 `gorm:"not null" ` - DateCreated int64 `gorm:"not null" ` -} - // TableName returns name of table func (m AssignGetInfo) TableName() string { return `1_assign_get_info` } // Get is retrieving model from database +func (m *AssignGetInfo) GetBalance(db *DbTransaction, wallet int64) (bool, decimal.Decimal, decimal.Decimal, error) { + + var mps []AssignGetInfo + var balance, total_balance decimal.Decimal balance = decimal.NewFromFloat(0) total_balance = decimal.NewFromFloat(0) err := GetDB(db).Table(m.TableName()). diff --git a/packages/model/language.go b/packages/model/language.go index 2fe271bf..43020564 100644 --- a/packages/model/language.go +++ b/packages/model/language.go @@ -23,16 +23,15 @@ func (l *Language) SetTablePrefix(prefix string) { l.ecosystem = converter.StrToInt64(prefix) } +// TableName returns name of table +func (l *Language) TableName() string { + if l.ecosystem == 0 { + l.ecosystem = 1 } return `1_languages` } // GetAll is retrieving all records from database -func (l *Language) GetAll(transaction *DbTransaction, prefix string) ([]Language, error) { - result := new([]Language) - err := GetDB(transaction).Table("1_languages").Where("ecosystem = ?", prefix).Order("name asc").Find(&result).Error - return *result, err -} // ToMap is converting model to map func (l *Language) ToMap() map[string]string { diff --git a/packages/model/pages.go b/packages/model/pages.go index cf278fb4..b335db7e 100644 --- a/packages/model/pages.go +++ b/packages/model/pages.go @@ -18,18 +18,15 @@ type Page struct { AppID int64 `gorm:"column:app_id;not null" json:"app_id,omitempty"` Conditions string `gorm:"not null" json:"conditions,omitempty"` } - p.ecosystem = 1 - } - return `1_pages` -} -// Get is retrieving model from database -func (p *Page) Get(name string) (bool, error) { - return isFound(DBConn.Where("ecosystem=? and name = ?", p.ecosystem, name).First(p)) +// SetTablePrefix is setting table prefix +func (p *Page) SetTablePrefix(prefix string) { + p.ecosystem = converter.StrToInt64(prefix) } -// Count returns count of records in table -func (p *Page) Count() (count int64, err error) { +// TableName returns name of table +func (p *Page) TableName() string { + if p.ecosystem == 0 { err = DBConn.Table(p.TableName()).Count(&count).Error return } diff --git a/packages/model/querycost/explain.go b/packages/model/querycost/explain.go index f1194f65..4a84accd 100644 --- a/packages/model/querycost/explain.go +++ b/packages/model/querycost/explain.go @@ -19,6 +19,14 @@ import ( ) // explainQueryCost is counting query execution time +func explainQueryCost(transaction *model.DbTransaction, withAnalyze bool, query string, args ...interface{}) (int64, error) { + var planStr string + explainTpl := "EXPLAIN (FORMAT JSON) %s" + if withAnalyze { + explainTpl = "EXPLAIN ANALYZE (FORMAT JSON) %s" + } + err := model.GetDB(transaction).Raw(fmt.Sprintf(explainTpl, query), args...).Row().Scan(&planStr) + switch { case err == sql.ErrNoRows: log.WithFields(log.Fields{"type": consts.DBError, "error": err, "query": query}).Error("no rows while explaining query") return 0, errors.New("No rows") @@ -31,12 +39,6 @@ import ( dec.UseNumber() if err := dec.Decode(&queryPlan); err != nil { log.WithFields(log.Fields{"type": consts.JSONUnmarshallError, "error": err}).Error("decoding query plan from JSON") - return 0, err - } - if len(queryPlan) == 0 { - log.Error("Query plan is empty") - return 0, errors.New("Query plan is empty") - } firstNode := queryPlan[0] var plan interface{} var ok bool diff --git a/packages/model/queue_tx.go b/packages/model/queue_tx.go index 4eea87d7..934ce6cb 100644 --- a/packages/model/queue_tx.go +++ b/packages/model/queue_tx.go @@ -23,23 +23,21 @@ func (qt *QueueTx) TableName() string { return "queue_tx" } -// Create is creating record of model -func (qt *QueueTx) Create() error { - return DBConn.Create(qt).Error +// DeleteTx is deleting tx +func (qt *QueueTx) DeleteTx(transaction *DbTransaction) error { + return GetDB(transaction).Delete(qt).Error } -// GetByHash is retrieving model from database by hash -func (qt *QueueTx) GetByHash(transaction *DbTransaction, hash []byte) (bool, error) { - return isFound(GetDB(transaction).Where("hash = ?", hash).First(qt)) +// Save is saving model +func (qt *QueueTx) Save(transaction *DbTransaction) error { + return GetDB(transaction).Save(qt).Error } -// DeleteQueueTxByHash is deleting queue tx by hash -func DeleteQueueTxByHash(transaction *DbTransaction, hash []byte) (int64, error) { - query := GetDB(transaction).Exec("DELETE FROM queue_tx WHERE hash = ?", hash) - return query.RowsAffected, query.Error +// Create is creating record of model +func (qt *QueueTx) Create() error { + return DBConn.Create(qt).Error } -// GetQueuedTransactionsCount counting queued transactions func GetQueuedTransactionsCount(hash []byte) (int64, error) { var rowsCount int64 err := DBConn.Table("queue_tx").Where("hash = ?", hash).Count(&rowsCount).Error diff --git a/packages/model/responecode.go b/packages/model/responecode.go new file mode 100644 index 00000000..e617d1f7 --- /dev/null +++ b/packages/model/responecode.go @@ -0,0 +1,149 @@ +package model + +import ( + "fmt" + "net/http" +) + +var ( + defaultStatus = http.StatusOK + //ErrEcosystemNotFound = errors.New("Ecosystem not found") + //errContract = errType{"E_CONTRACT", "There is not %s contract", http.StatusNotFound} + //errDBNil = errType{"E_DBNIL", "DB is nil", defaultStatus} + //errDeletedKey = errType{"E_DELETEDKEY", "The key is deleted", http.StatusForbidden} + //errEcosystem = errType{"E_ECOSYSTEM", "Ecosystem %d doesn't exist", defaultStatus} + //errEmptyPublic = errType{"E_EMPTYPUBLIC", "Public key is undefined", http.StatusBadRequest} + //errKeyNotFound = errType{"E_KEYNOTFOUND", "Key has not been found", http.StatusNotFound} + //errEmptySign = errType{"E_EMPTYSIGN", "Signature is undefined", defaultStatus} + //errHashWrong = errType{"E_HASHWRONG", "Hash is incorrect", http.StatusBadRequest} + //errHashNotFound = errType{"E_HASHNOTFOUND", "Hash has not been found", defaultStatus} + //errHeavyPage = errType{"E_HEAVYPAGE", "This page is heavy", defaultStatus} + //errInstalled = errType{"E_INSTALLED", "Chain is already installed", defaultStatus} + //errInvalidWallet = errType{"E_INVALIDWALLET", "Wallet %s is not valid", http.StatusBadRequest} + //errLimitForsign = errType{"E_LIMITFORSIGN", "Length of forsign is too big (%d)", defaultStatus} + //errLimitTxSize = errType{"E_LIMITTXSIZE", "The size of tx is too big (%d)", defaultStatus} + //errNotFound = errType{"E_NOTFOUND", "Page not found", http.StatusNotFound} + //errNotFoundRecord = errType{"E_NOTFOUND", "Record not found", http.StatusNotFound} + //errParamNotFound = errType{"E_PARAMNOTFOUND", "Parameter %s has not been found", http.StatusNotFound} + //errPermission = errType{"E_PERMISSION", "Permission denied", http.StatusUnauthorized} + //errQuery = errType{"E_QUERY", "DB query is wrong", http.StatusInternalServerError} + //errRecovered = errType{"E_RECOVERED", "API recovered", http.StatusInternalServerError} + //errServer = errType{"E_SERVER", "Server error", defaultStatus} + //errSignature = errType{"E_SIGNATURE", "Signature is incorrect", http.StatusBadRequest} + //errUnknownSign = errType{"E_UNKNOWNSIGN", "Unknown signature", defaultStatus} + //errStateLogin = errType{"E_STATELOGIN", "%s is not a membership of ecosystem %s", http.StatusForbidden} + //errTableNotFound = errType{"E_TABLENOTFOUND", "Table %s has not been found", http.StatusNotFound} + //errToken = errType{"E_TOKEN", "Token is not valid", defaultStatus} + //errTokenExpired = errType{"E_TOKENEXPIRED", "Token is expired by %s", http.StatusUnauthorized} + //errUnauthorized = errType{"E_UNAUTHORIZED", "Unauthorized", http.StatusUnauthorized} + //errUndefineval = errType{"E_UNDEFINEVAL", "Value %s is undefined", defaultStatus} + //errUnknownUID = errType{"E_UNKNOWNUID", "Unknown uid", defaultStatus} + //errOBS = errType{"E_OBS", "Virtual Dedicated Ecosystem %d doesn't exist", defaultStatus} + //errOBSCreated = errType{"E_OBSCREATED", "Virtual Dedicated Ecosystem is already created", http.StatusBadRequest} + //errRequestNotFound = errType{"E_REQUESTNOTFOUND", "Request %s doesn't exist", defaultStatus} + //errUpdating = errType{"E_UPDATING", "Node is updating blockchain", http.StatusServiceUnavailable} + //errStopping = errType{"E_STOPPING", "Network is stopping", http.StatusServiceUnavailable} + //errNotImplemented = errType{"E_NOTIMPLEMENTED", "Not implemented", http.StatusNotImplemented} + //errParamMoneyDigit = errType{"E_PARAMMONEYDIGIT", "The number of decimal places cannot be exceeded ( %s )", http.StatusBadRequest} + //errDiffKey = CodeType{"E_DIFKEY", "Sender's key is different from tx key", defaultStatus} + //errBannded = errType{"E_BANNED", "The key is banned till %s", http.StatusForbidden} + //errCheckRole = errType{"E_CHECKROLE", "Access denied", http.StatusForbidden} + //errNewUser = errType{"E_NEWUSER", "Can't create a new user", http.StatusUnauthorized} + CodeSystembusy = CodeType{-1, "System is busy", http.StatusOK, ""} + CodeSuccess = CodeType{0, "Success", http.StatusOK, "OK"} + //CodeFileNotExists = CodeType{40001, "File %s not exists", http.StatusOK, ""} + //CodeFileFormatNotSupports = CodeType{40002, "File %s format is not supported", http.StatusOK, ""} + CodeIlgmediafiletype = CodeType{40003, "illegal media file type ", http.StatusOK, ""} + CodeIlgfiletype = CodeType{40004, "illegal file type ", http.StatusOK, ""} + CodeFilesize = CodeType{40005, "illegal file size ", http.StatusOK, ""} + CodeImagesize = CodeType{40006, "illegal image file size ", http.StatusOK, ""} + CodeVoicesize = CodeType{40007, "illegal voice file size ", http.StatusOK, ""} + CodeVideosize = CodeType{40008, "illegal video file size ", http.StatusOK, ""} + CodeRequestformat = CodeType{40009, "illegal request format ", http.StatusOK, ""} + CodeThumbnailfilesize = CodeType{400010, "illegal thumbnail file size ", http.StatusOK, ""} + CodeUrllength = CodeType{400011, "illegal URL length ", http.StatusOK, ""} + CodeMultimediafileempty = CodeType{400012, "The multimedia file is empty ", http.StatusOK, ""} + CodePostpacketempty = CodeType{400013, "POST packet is empty ", http.StatusOK, ""} + CodeContentempty = CodeType{400014, "The content of the graphic message is empty. ", http.StatusOK, ""} + CodeTextcmpty = CodeType{400015, "text message content is empty ", http.StatusOK, ""} + CodeMultimediasizelimit = CodeType{400016, "multimedia file size exceeds limit ", http.StatusOK, ""} + CodeParamNotNull = CodeType{400017, "Param message content exceeds limit ", http.StatusOK, ""} + CodeParamOutRange = CodeType{400018, "Param out of range ", http.StatusOK, ""} + CodeParam = CodeType{400019, "Param error ", http.StatusOK, ""} + CodeParamNotExists = CodeType{400020, "Param is exists ", http.StatusOK, ""} + CodeParamType = CodeType{400021, "Param type error ", http.StatusOK, ""} + CodeParamKeyConflict = CodeType{400022, "Param Keyword conflict error ", http.StatusOK, ""} + CodeRecordExists = CodeType{400023, "Record already exists ", http.StatusOK, ""} + CodeRecordNotExists = CodeType{400024, "Record not exists error ", http.StatusOK, ""} + CodeNewRecordNotRelease = CodeType{400025, "New Record not Release error ", http.StatusOK, ""} + CodeReleaseRule = CodeType{400026, "Release rule error ", http.StatusOK, ""} + CodeDeleteRule = CodeType{400027, "Delete Record delete rule error ", http.StatusOK, ""} + CodeHelpDirNotExists = CodeType{400028, "Help parentdir not exists error ", http.StatusOK, ""} + + CodeDBfinderr = CodeType{400029, "DB find error ", http.StatusOK, ""} + CodeDBcreateerr = CodeType{400030, "DB create error ", http.StatusOK, ""} + CodeDBupdateerr = CodeType{400031, "DB update error ", http.StatusOK, ""} + CodeDBdeleteerr = CodeType{400032, "DB delete error ", http.StatusOK, ""} + CodeDBopertionerr = CodeType{400033, "DB opertion error ", http.StatusOK, ""} + CodeJsonformaterr = CodeType{400034, "Json format error ", http.StatusOK, ""} + CodeBodyformaterr = CodeType{400035, "Body format error ", http.StatusOK, ""} + + CodeFileNotExists = CodeType{400036, "File not exists", http.StatusOK, ""} + //CodeFileFormatNotSupports = CodeType{40002, "File %s format is not supported", http.StatusOK, ""} + CodeFileExists = CodeType{400037, "File already exists", http.StatusOK, ""} + CodeFileFormatNotSupports = CodeType{400038, "File format is not supported", http.StatusOK, ""} + CodeFileCreated = CodeType{400039, "Create File is not supported ", http.StatusOK, ""} + CodeFileOpen = CodeType{400039, "Open File is not supported", http.StatusOK, ""} + CodeCheckParam = CodeType{400040, "Param error: ", http.StatusOK, ""} + CodeGenerateMine = CodeType{400041, "new miner generate faile ", http.StatusOK, ""} + CodeImportMine = CodeType{400042, "import miner faile ", http.StatusOK, ""} + CodeBooltype = CodeType{400043, "bool type error ", http.StatusOK, ""} + + CodeUpdateRule = CodeType{400044, "rule error ", http.StatusOK, ""} + CodePermissionDenied = CodeType{400045, "Permission denied ", http.StatusOK, ""} + CodeNotMineDevidBindActiveid = CodeType{400046, "not mine devid boind Activeid ", http.StatusOK, ""} + CodeSignError = CodeType{400047, "sign err ", http.StatusOK, ""} + //CodeNotMineDevidBindActiveid = CodeType{400046, "not mine devid boind Activeid ", http.StatusOK, ""} + //CodeReleaseRule = CodeType{400042, "Release rule conflict %s ", http.StatusOK, ""} +//CodeGenerateMine = CodeType{400041, "new miner generate faile ", http.StatusOK, ""} +//CodeGenerateMine = CodeType{400041, "new miner generate faile ", http.StatusOK, ""} +) + +type CodeType struct { + Code int `json:"code"` + Message string `json:"message"` + Status int `json:"status"` + Msg string `json:"msg"` +} + +// +type errType struct { + Err string `json:"error"` + Message string `json:"msg"` + Status int `json:"-"` +} + + et.Message = fmt.Sprintf(et.Message, v...) + return et +} + +func (ct CodeType) Errorf(err error) CodeType { + et, ok := err.(errType) + if !ok { + et.Message = err.Error() + } + ct.Message = fmt.Sprintln(ct.Message, et.Message) + ct.Msg = http.StatusText(ct.Status) + return ct +} + +func (ct CodeType) String(dat string) CodeType { + ct.Message += " " + dat + ct.Msg = http.StatusText(ct.Status) + return ct +} + +func (ct CodeType) Success() CodeType { + ct.Msg = http.StatusText(ct.Status) + return ct +} diff --git a/packages/model/signatures.go b/packages/model/signatures.go index 5836c047..a037e805 100644 --- a/packages/model/signatures.go +++ b/packages/model/signatures.go @@ -11,6 +11,14 @@ type Signature struct { Name string `gorm:"primary_key;not null;size:255"` Value string `gorm:"not null;type:jsonb"` Conditions string `gorm:"not null"` -func (s *Signature) Get(name string) (bool, error) { - return isFound(DBConn.Where("name = ?", name).First(s)) +} + +// SetTablePrefix is setting table prefix +func (s *Signature) SetTablePrefix(prefix string) { + s.tableName = prefix + "_signatures" +} + +// TableName returns name of table +func (s *Signature) TableName() string { + return s.tableName } diff --git a/packages/model/system_parameters.go b/packages/model/system_parameters.go index a65209bc..b562b485 100644 --- a/packages/model/system_parameters.go +++ b/packages/model/system_parameters.go @@ -61,6 +61,9 @@ func GetAllSystemParameters(transaction *DbTransaction) ([]SystemParameter, erro // ToMap is converting SystemParameter to map func (sp *SystemParameter) ToMap() map[string]string { + result := make(map[string]string, 0) + result["name"] = sp.Name + result["value"] = sp.Value result["conditions"] = sp.Conditions return result } @@ -103,12 +106,3 @@ func (sp *SystemParameter) GetPoolBlockRate(dbt *DbTransaction) (int64, error) { f, err := sp.GetTransaction(dbt, `pool_block_rate`) if err != nil { return 0, err - } - if f { - if len(sp.Value) > 0 { - return strconv.ParseInt(sp.Value, 10, 64) - } - } - - return 0, errors.New("pool_block_rate not found") -} diff --git a/packages/network/httpserver/max_body.go b/packages/network/httpserver/max_body.go new file mode 100644 index 00000000..0b76904a --- /dev/null +++ b/packages/network/httpserver/max_body.go @@ -0,0 +1,10 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) IBAX. All rights reserved. + * See LICENSE in the project root for license information. + r.Body = http.MaxBytesReader(w, r.Body, h.n) + h.h.ServeHTTP(w, r) +} + +func NewMaxBodyReader(h http.Handler, n int64) http.Handler { + return &MaxBodyReader{h, n} +} diff --git a/packages/network/tcpserver/type2.go b/packages/network/tcpserver/type2.go index 76821905..2df2e2f6 100644 --- a/packages/network/tcpserver/type2.go +++ b/packages/network/tcpserver/type2.go @@ -62,8 +62,14 @@ func Type2(rw io.ReadWriter) error { } //// Type2 serves requests from disseminator +//func Type2(rw io.ReadWriter) (*network.DisTrResponse, error) { +// r := &network.DisRequest{} +// if err := r.Read(rw); err != nil { +// return nil, err // } // +// binaryData := r.Data +// // take the transactions from usual users but not nodes. // if int64(len(binaryData)) > syspar.GetMaxTxSize() { // log.WithFields(log.Fields{"type": consts.ParameterExceeded, "max_size": syspar.GetMaxTxSize(), "size": len(binaryData)}).Error("transaction size exceeds max size") // return nil, utils.ErrInfo("len(txBinData) > max_tx_size") diff --git a/packages/smart/math.go b/packages/smart/math.go index d82fe048..9a9d68a0 100644 --- a/packages/smart/math.go +++ b/packages/smart/math.go @@ -52,6 +52,22 @@ func Log(x interface{}) (float64, error) { return 0, err } if fx = math.Log(fx); isValidFloat(fx) { + return fx, nil + } + return 0, errFloatResult +} + +// Log10 returns the decimal logarithm of x +func Log10(x interface{}) (float64, error) { + fx, err := parseFloat(x) + if err != nil { + return 0, err + } + if fx = math.Log10(fx); isValidFloat(fx) { + return fx, nil + } + return 0, errFloatResult +} // Pow returns x**y, the base-x exponential of y func Pow(x, y interface{}) (float64, error) { @@ -73,12 +89,6 @@ func Pow(x, y interface{}) (float64, error) { func Round(x interface{}) (int64, error) { fx, err := parseFloat(x) if err != nil { - return 0, err - } - if fx = math.Round(fx); isValidFloat(fx) { - return int64(fx), nil - } - return 0, errFloatResult } // Sqrt returns the square root of x diff --git a/packages/smart/queryBuilder/query_builder.go b/packages/smart/queryBuilder/query_builder.go index e17f7837..9a109c13 100644 --- a/packages/smart/queryBuilder/query_builder.go +++ b/packages/smart/queryBuilder/query_builder.go @@ -2,6 +2,25 @@ * Copyright (c) IBAX. All rights reserved. * See LICENSE in the project root for license information. *--------------------------------------------------------------------------------------------*/ +package queryBuilder + +import ( + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" + + "github.com/IBAX-io/go-ibax/packages/conf/syspar" + "github.com/IBAX-io/go-ibax/packages/consts" + "github.com/IBAX-io/go-ibax/packages/converter" + "github.com/IBAX-io/go-ibax/packages/types" + + log "github.com/sirupsen/logrus" +) + +const ( prefTimestamp = "timestamp" prefTimestampSpace = "timestamp " ) @@ -106,24 +125,6 @@ func (b *SQLQueryBuilder) GetSelectExpr() (string, error) { } whereExpr, err := b.GetSQLWhereExpr() - if err != nil { - b.WithFields(log.Fields{"error": err}).Error("on getting sql where statement") - return "", err - } - return fmt.Sprintf(`SELECT %s FROM "%s" %s`, fieldsExpr, b.Table, whereExpr), nil -} - -func (b *SQLQueryBuilder) GetSQLSelectFieldsExpr() (string, error) { - if err := b.Prepare(); err != nil { - return "", err - } - - sqlFields := make([]string, 0, len(b.Fields)+1) - sqlFields = append(sqlFields, "id") - - for i := range b.Fields { - b.Fields[i] = strings.TrimSpace(strings.ToLower(b.Fields[i])) - sqlFields = append(sqlFields, toSQLField(b.Fields[i])) } return strings.Join(sqlFields, ","), nil diff --git a/packages/smart/queryBuilder/query_builder_test.go b/packages/smart/queryBuilder/query_builder_test.go index 83d2e9f1..f022e6d8 100644 --- a/packages/smart/queryBuilder/query_builder_test.go +++ b/packages/smart/queryBuilder/query_builder_test.go @@ -9,11 +9,6 @@ import ( "testing" "github.com/IBAX-io/go-ibax/packages/types" - - log "github.com/sirupsen/logrus" -) - -// query="SELECT ,,,id,amount,\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\"ecosystem\" // FROM \"1_keys\" \nWHERE AND id = -6752330173818123413 AND ecosystem = '1'\n" // fields="[+amount]" @@ -22,6 +17,11 @@ import ( // whereF="[id]" // whereV="[-6752330173818123413]" +type TestKeyTableChecker struct { + Val bool +} + +func (tc TestKeyTableChecker) IsKeyTable(tableName string) bool { return tc.Val } func TestSqlFields(t *testing.T) { diff --git a/packages/smart/selective.go b/packages/smart/selective.go index 58eac664..ee872088 100644 --- a/packages/smart/selective.go +++ b/packages/smart/selective.go @@ -88,21 +88,6 @@ func (sc *SmartContract) selectiveLoggingAndUpd(fields []string, ivalues []inter if sqlBuilder.IsEmptyWhere() { logger.WithFields(log.Fields{"type": consts.NotFound, "error": errWhereUpdate}).Error("update without where") - return 0, "", errWhereUpdate - } - } - - logger.WithFields(log.Fields{"error": err}).Error("on generate rollback info string for update") - return 0, "", err - } - - updateExpr, err := sqlBuilder.GetSQLUpdateExpr(logData) - if err != nil { - logger.WithFields(log.Fields{"error": err}).Error("on getting update expression for update") - return 0, "", err - } - - whereExpr, err := sqlBuilder.GetSQLWhereExpr() if err != nil { logger.WithFields(log.Fields{"error": err}).Error("on getting where expression for update") return 0, "", err diff --git a/packages/transaction/custom/first_block.go b/packages/transaction/custom/first_block.go index e696d407..4647ba02 100644 --- a/packages/transaction/custom/first_block.go +++ b/packages/transaction/custom/first_block.go @@ -45,6 +45,12 @@ func (t *FirstBlockTransaction) Init() error { func (t *FirstBlockTransaction) Validate() error { return nil } + +// Action is fires first block +func (t *FirstBlockTransaction) Action() error { + logger := t.Logger + data := t.Data.(*consts.FirstBlock) + keyID := crypto.Address(data.PublicKey) nodeKeyID := crypto.Address(data.NodePublicKey) err := model.ExecSchemaEcosystem(nil, firstEcosystemID, keyID, ``, keyID, firstAppID) if err != nil { @@ -102,16 +108,6 @@ func (t *FirstBlockTransaction) Validate() error { id, syspar.SysString(`default_ecosystem_menu`), `default`).Error if err != nil { logger.WithFields(log.Fields{"type": consts.DBError, "error": err}).Error("inserting default menu") - return utils.ErrInfo(err) - } - err = smart.LoadContract(t.DbTransaction, 1) - if err != nil { - return utils.ErrInfo(err) - } - if err := syspar.SysTableColType(t.DbTransaction); err != nil { - return utils.ErrInfo(err) - } - syspar.SetFirstBlockData(data) return nil } diff --git a/packages/utils/metric/metrics.go b/packages/utils/metric/metrics.go index 5dc9392f..840771b2 100644 --- a/packages/utils/metric/metrics.go +++ b/packages/utils/metric/metrics.go @@ -49,6 +49,20 @@ func CollectMetricDataForEcosystemTables(timeBlock int64) (metricValues []*Value Value: pagesCount, }) + m := &model.Member{} + m.SetTablePrefix(tablePrefix) + if membersCount, err = m.Count(); err != nil { + log.WithFields(log.Fields{"error": err, "type": consts.DBError}).Error("get count of members") + return nil, err + } + metricValues = append(metricValues, &Value{ + Time: unixDate, + Metric: metricEcosystemMembers, + Key: tablePrefix, + Value: membersCount, + }) + } + return metricValues, nil } @@ -71,6 +85,3 @@ func CollectMetricDataForEcosystemTx(timeBlock int64) (metricValues []*Value, er Value: item.Count, }) } - - return metricValues, nil -} diff --git a/packages/utils/tx/builder.go b/packages/utils/tx/builder.go index e74923ae..8e8ba3d9 100644 --- a/packages/utils/tx/builder.go +++ b/packages/utils/tx/builder.go @@ -55,8 +55,6 @@ func CreateTransaction(data, hash []byte, keyID, tnow int64) error { tx := &model.Transaction{ Hash: hash, Data: data[:], - Type: consts.TxTypeApiContract, - KeyID: keyID, HighRate: model.TransactionRateOnBlock, Time: tnow, } @@ -73,6 +71,12 @@ func CreateDelayTransactionHighRate(data, hash []byte, keyID, highRate int64) *m t := int8(highRate) tx := &model.Transaction{ Hash: hash, + Data: data[:], + Type: getTxTxType(t), + KeyID: keyID, + HighRate: model.GetTxRateByTxType(t), + } + return tx } func getTxTxType(rate int8) int8 {