forked from aergoio/aergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chainanchor.go
109 lines (91 loc) · 2.09 KB
/
chainanchor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package chain
import (
"github.com/aergoio/aergo/internal/enc"
"github.com/aergoio/aergo/types"
)
type ChainAnchor []([]byte)
const (
MaxAnchors = 32
//MaxAnchors = 1000000
Skip = 16
)
// returns anchor blocks of chain
// use config
func (cs *ChainService) getAnchorsNew() (ChainAnchor, types.BlockNo, error) {
//from top : 8 * 32 = 256
anchors := make(ChainAnchor, 0)
cnt := MaxAnchors
logger.Debug().Msg("get anchors")
blkNo := cs.getBestBlockNo()
var lastNo types.BlockNo
LOOP:
for i := 0; i < cnt; i++ {
blockHash, err := cs.getHashByNo(blkNo)
if err != nil {
logger.Info().Msg("assertion - hash get failed")
// assertion!
return nil, 0, err
}
anchors = append(anchors, blockHash)
lastNo = blkNo
logger.Debug().Uint64("no", blkNo).Msg("anchor added")
switch {
case blkNo == 0:
break LOOP
case blkNo < Skip:
blkNo = 0
default:
blkNo -= Skip
}
}
return anchors, lastNo, nil
}
// returns anchor blocks of chain
// use config
func (cs *ChainService) getAnchorsFromHash(blockHash []byte) ChainAnchor {
/* TODO: use config */
anchors := make(ChainAnchor, 0, 1000)
anchors = append(anchors, blockHash)
// collect 10 latest hashes
latestNo := cs.getBestBlockNo()
for i := 0; i < 10; i++ {
blockHash, err := cs.getHashByNo(latestNo)
if err != nil {
logger.Info().Msg("assertion - hash get failed")
// assertion!
return nil
}
logger.Debug().Uint64("no", latestNo).Str("hash", enc.ToString(blockHash)).Msg("anchor")
anchors = append(anchors, blockHash)
if latestNo == 0 {
return anchors
}
latestNo--
}
count := MaxAnchorCount
// collect exponential
var dec types.BlockNo = 1
for i := 0; i < count; i++ {
blockHash, err := cs.getHashByNo(latestNo)
if err != nil {
// assertion!
return nil
}
logger.Debug().Uint64("no", latestNo).Str("hash", enc.ToString(blockHash)).Msg("anchor")
anchors = append(anchors, blockHash)
if latestNo <= dec {
if latestNo == 0 {
break
}
latestNo = 0
} else {
latestNo -= dec
dec *= 2
}
}
return anchors
}