OSDN Git Service

finish but untest calDiff, due to need work on other parts ASAP
authorpaladz <453256728@qq.com>
Mon, 25 Sep 2017 05:59:04 +0000 (13:59 +0800)
committerpaladz <453256728@qq.com>
Mon, 25 Sep 2017 05:59:04 +0000 (13:59 +0800)
consensus/difficulty.go
consensus/general.go
mining/mining.go

index 3d437b5..f1e2b5f 100644 (file)
@@ -88,12 +88,22 @@ func CheckProofOfWork(hash *bc.Hash, bits uint64) bool {
        return false
 }
 
-func CalcNextRequiredDifficulty(bh *legacy.BlockHeader) uint64 {
-       if bh == nil {
+func CalcNextRequiredDifficulty(lastBH, prevBH *legacy.BlockHeader) uint64 {
+       return uint64(2161727821138738707)
+
+       //TODO: test it and enable it
+       if lastBH == nil {
                return powMinBits
-       } else if (bh.Height+1)%blocksPerRetarget != 0 {
-               return bh.Bits
+       } else if (lastBH.Height+1)%blocksPerRetarget != 0 {
+               return lastBH.Bits
        }
 
-       return uint64(2161727821138738707)
+       actualTimespan := int64(lastBH.Time().Sub(prevBH.Time()).Seconds())
+       oldTarget := CompactToBig(lastBH.Bits)
+       newTarget := new(big.Int).Mul(oldTarget, big.NewInt(actualTimespan))
+       targetTimeSpan := int64(blocksPerRetarget * targetSecondsPerBlock)
+       newTarget.Div(newTarget, big.NewInt(targetTimeSpan))
+       newTargetBits := BigToCompact(newTarget)
+
+       return newTargetBits
 }
index 6432df4..2ae80eb 100644 (file)
@@ -17,7 +17,7 @@ const (
        // config for pow mining
        powMinBits            = uint64(2161727821138738707)
        blocksPerRetarget     = uint64(1024)
-       targetSecondsPerBlock = int64(60)
+       targetSecondsPerBlock = uint64(60)
 )
 
 // define the BTM asset id, the soul asset of Bytom
index ffbd858..ab509fb 100644 (file)
@@ -78,7 +78,7 @@ func NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, addr []byte) (
                        PreviousBlockHash: preBlockHash,
                        TimestampMS:       bc.Millis(time.Now()),
                        BlockCommitment:   legacy.BlockCommitment{},
-                       Bits:              consensus.CalcNextRequiredDifficulty(),
+                       Bits:              consensus.CalcNextRequiredDifficulty(nil, nil),
                },
        }
        newSnap.PruneNonces(b.BlockHeader.TimestampMS)