keva-stratum/stratum/blocks.go

64 lines
1.7 KiB
Go
Raw Normal View History

2015-07-05 09:49:07 +00:00
package stratum
import (
"bytes"
"encoding/binary"
"encoding/hex"
"log"
2018-02-10 00:08:43 +00:00
"math/big"
2019-03-09 08:24:32 +00:00
"../cnutil"
2015-07-05 09:49:07 +00:00
)
type BlockTemplate struct {
2018-02-10 00:08:43 +00:00
diffInt64 int64
2016-12-07 07:00:18 +00:00
height int64
difficulty *big.Int
2016-12-07 07:00:18 +00:00
reservedOffset int
prevHash string
buffer []byte
2015-07-05 09:49:07 +00:00
}
2016-12-06 12:07:45 +00:00
func (b *BlockTemplate) nextBlob(extraNonce uint32, instanceId []byte) string {
2015-07-05 09:49:07 +00:00
extraBuff := new(bytes.Buffer)
binary.Write(extraBuff, binary.BigEndian, extraNonce)
2016-12-06 12:07:45 +00:00
2016-12-07 07:00:18 +00:00
blobBuff := make([]byte, len(b.buffer))
copy(blobBuff, b.buffer)
copy(blobBuff[b.reservedOffset+4:b.reservedOffset+7], instanceId)
copy(blobBuff[b.reservedOffset:], extraBuff.Bytes())
blob := cnutil.ConvertBlob(blobBuff)
2016-12-06 12:07:45 +00:00
return hex.EncodeToString(blob)
2015-07-05 09:49:07 +00:00
}
func (s *StratumServer) fetchBlockTemplate() bool {
2016-12-06 17:16:57 +00:00
r := s.rpc()
reply, err := r.GetBlockTemplate(8, s.config.Address)
2015-07-05 09:49:07 +00:00
if err != nil {
log.Printf("Error while refreshing block template: %s", err)
return false
}
t := s.currentBlockTemplate()
2016-12-07 07:00:18 +00:00
if t != nil && t.prevHash == reply.PrevHash {
2015-07-05 09:49:07 +00:00
// Fallback to height comparison
2016-12-07 07:00:18 +00:00
if len(reply.PrevHash) == 0 && reply.Height > t.height {
2016-12-07 07:11:08 +00:00
log.Printf("New block to mine on %s at height %v, diff: %v", r.Name, reply.Height, reply.Difficulty)
2015-07-05 09:49:07 +00:00
} else {
return false
}
} else {
2016-12-06 17:16:57 +00:00
log.Printf("New block to mine on %s at height %v, diff: %v, prev_hash: %s", r.Name, reply.Height, reply.Difficulty, reply.PrevHash)
2015-07-05 09:49:07 +00:00
}
newTemplate := BlockTemplate{
2018-02-10 00:08:43 +00:00
diffInt64: reply.Difficulty,
difficulty: big.NewInt(reply.Difficulty),
2016-12-07 07:00:18 +00:00
height: reply.Height,
prevHash: reply.PrevHash,
reservedOffset: reply.ReservedOffset,
2015-07-05 09:49:07 +00:00
}
2016-12-07 07:00:18 +00:00
newTemplate.buffer, _ = hex.DecodeString(reply.Blob)
2015-07-05 09:49:07 +00:00
s.blockTemplate.Store(&newTemplate)
return true
}