github.com/annchain/OG@v0.0.9/core/confirm_status.go (about) 1 // Copyright © 2019 Annchain Authors <EMAIL ADDRESS> 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 package core 15 16 import ( 17 "fmt" 18 "sync" 19 "time" 20 ) 21 22 type ConfirmStatus struct { 23 TxNum uint64 24 ConfirmNum uint64 25 Confirm time.Duration 26 mu sync.RWMutex 27 initTime time.Time 28 RefreshTime time.Duration 29 } 30 31 type ConfirmInfo struct { 32 ConfirmTime string `json:"confirm_time"` 33 ConfirmRate string `json:"confirm_rate"` 34 } 35 36 func (c *ConfirmStatus) AddTxNum() { 37 c.mu.Lock() 38 defer c.mu.Unlock() 39 if time.Since(c.initTime) > c.RefreshTime { 40 c.TxNum = 0 41 c.ConfirmNum = 0 42 c.Confirm = time.Duration(0) 43 c.initTime = time.Now() 44 } 45 c.TxNum++ 46 } 47 48 func (c *ConfirmStatus) AddConfirm(d time.Duration) { 49 c.mu.Lock() 50 defer c.mu.Unlock() 51 52 c.Confirm += d 53 c.ConfirmNum++ 54 } 55 56 func (c *ConfirmStatus) GetInfo() *ConfirmInfo { 57 var info = &ConfirmInfo{} 58 c.mu.RLock() 59 defer c.mu.RUnlock() 60 61 if c.TxNum != 0 { 62 rate := float64(c.ConfirmNum*100) / float64(c.TxNum) 63 if rate == 1 { 64 info.ConfirmRate = "100%" 65 } else if rate < 98 { 66 info.ConfirmRate = fmt.Sprintf("%2d", int(rate)) + "%" 67 } else { 68 info.ConfirmRate = fmt.Sprintf("%3f", rate) + "%" 69 } 70 } 71 if c.ConfirmNum != 0 { 72 info.ConfirmTime = (c.Confirm / time.Duration(c.ConfirmNum)).String() 73 } 74 return info 75 }