steem-block-db/db.go

87 lines
2.4 KiB
Go

package main
import log "github.com/sirupsen/logrus"
//import "io/ioutil"
import "fmt"
import "strconv"
const appPrefix = "steem-block-fetcher"
type SteemDataStorer interface {
SetCurrentBlockHeight() error
ForceSetCurrentBlockHeight(BlockNumber) error
CurrentBlockHeight() BlockNumber
HaveOpsForBlock(BlockNumber) bool
StoreBlockOps(BlockNumber, *[]byte) error
}
// SteemDataStore is the object with which the rest of this tool interacts
type SteemDataStore struct {
kv KVStorer
}
func NewSteemDataStore(dir string) *SteemDataStore {
self := new(SteemDataStore)
self.kv = NewRedisKVStore()
return self
}
func (self *SteemDataStore) ForceSetCurrentBlockHeight(blockNum BlockNumber) error {
keyname := fmt.Sprintf("%s:global:CurrentBlockHeight", appPrefix)
value := fmt.Sprintf("%d", blockNum)
return self.kv.Put(&keyname, &value)
}
// this function searches for the highest contiguously stored blocknum
// and updates the memo in the db
func (self *SteemDataStore) SetCurrentBlockHeight() error {
nextVal := self.FindHighestContiguousBlockInDb(self.CurrentBlockHeight())
keyname := fmt.Sprintf("%s:global:CurrentBlockHeight", appPrefix)
value := fmt.Sprintf("%d", nextVal)
log.Infof("updating our current highest block in db to %d", nextVal)
return self.kv.Put(&keyname, &value)
}
func (self *SteemDataStore) FindHighestContiguousBlockInDb(from BlockNumber) BlockNumber {
last := from
var keyname string
var try BlockNumber
for {
try = BlockNumber(uint64(last) + 1)
keyname = fmt.Sprintf("%s:BlockOps:%d", appPrefix, try)
exists, _ := self.kv.Exists(&keyname)
if exists == false {
log.Debugf("cannot find block %d in db, highest found is %d", try, last)
return last
} else {
last = try
}
}
}
func (self *SteemDataStore) StoreBlockOps(blockNum BlockNumber, blockOps *[]byte) error {
keyname := fmt.Sprintf("%s:BlockOps:%d", appPrefix, blockNum)
value := string(*blockOps)
return self.kv.Put(&keyname, &value)
}
func (self *SteemDataStore) HaveOpsForBlock(blockNum BlockNumber) bool {
panic("unimplemented")
}
func (self *SteemDataStore) CurrentBlockHeight() BlockNumber {
keyname := fmt.Sprintf("%s:global:CurrentBlockHeight", appPrefix)
val, err := self.kv.Get(&keyname)
if err != nil {
// assume this is key not found, initialize key to default
self.ForceSetCurrentBlockHeight(0)
// retry
return self.CurrentBlockHeight()
}
intval, err := strconv.ParseUint(*val, 10, 64)
return BlockNumber(intval)
}