-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
266 lines (217 loc) · 7.79 KB
/
utils.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package genesis
import (
"encoding/hex"
"fmt"
"io/ioutil"
"math/big"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"github.com/esportzvio/frietorchain/command"
"github.com/esportzvio/frietorchain/consensus/polybft"
"github.com/esportzvio/frietorchain/consensus/polybft/bitmap"
"github.com/esportzvio/frietorchain/consensus/polybft/validator"
"github.com/esportzvio/frietorchain/consensus/polybft/wallet"
"github.com/esportzvio/frietorchain/secrets"
"github.com/esportzvio/frietorchain/secrets/helper"
"github.com/esportzvio/frietorchain/secrets/local"
"github.com/esportzvio/frietorchain/types"
"github.com/hashicorp/go-hclog"
)
const (
StatError = "StatError"
ExistsError = "ExistsError"
)
// GenesisGenError is a specific error type for generating genesis
type GenesisGenError struct {
message string
errorType string
}
// GetMessage returns the message of the genesis generation error
func (g *GenesisGenError) GetMessage() string {
return g.message
}
// GetType returns the type of the genesis generation error
func (g *GenesisGenError) GetType() string {
return g.errorType
}
// verifyGenesisExistence checks if the genesis file at the specified path is present
func verifyGenesisExistence(genesisPath string) *GenesisGenError {
_, err := os.Stat(genesisPath)
if err != nil && !os.IsNotExist(err) {
return &GenesisGenError{
message: fmt.Sprintf("failed to stat (%s): %v", genesisPath, err),
errorType: StatError,
}
}
if !os.IsNotExist(err) {
return &GenesisGenError{
message: fmt.Sprintf("genesis file at path (%s) already exists", genesisPath),
errorType: ExistsError,
}
}
return nil
}
type premineInfo struct {
address types.Address
amount *big.Int
}
// parsePremineInfo parses provided premine information and returns premine address and amount
func parsePremineInfo(premineInfoRaw string) (*premineInfo, error) {
var (
address types.Address
amount = command.DefaultPremineBalance
err error
)
if delimiterIdx := strings.Index(premineInfoRaw, ":"); delimiterIdx != -1 {
// <addr>:<balance>
valueRaw := premineInfoRaw[delimiterIdx+1:]
amount, err = types.ParseUint256orHex(&valueRaw)
if err != nil {
return nil, fmt.Errorf("failed to parse amount %s: %w", valueRaw, err)
}
address = types.StringToAddress(premineInfoRaw[:delimiterIdx])
} else {
// <addr>
address = types.StringToAddress(premineInfoRaw)
}
return &premineInfo{address: address, amount: amount}, nil
}
// parseTrackerStartBlocks parses provided event tracker start blocks configuration.
// It is set in a following format: <contractAddress>:<startBlock>.
// In case smart contract address isn't provided in the string, it is assumed its starting block is 0 implicitly.
func parseTrackerStartBlocks(trackerStartBlocksRaw []string) (map[types.Address]uint64, error) {
trackerStartBlocksConfig := make(map[types.Address]uint64, len(trackerStartBlocksRaw))
for _, startBlockRaw := range trackerStartBlocksRaw {
delimiterIdx := strings.Index(startBlockRaw, ":")
if delimiterIdx == -1 {
return nil, fmt.Errorf("invalid event tracker start block configuration provided: %s", trackerStartBlocksRaw)
}
// <contractAddress>:<startBlock>
address := types.StringToAddress(startBlockRaw[:delimiterIdx])
startBlockRaw := startBlockRaw[delimiterIdx+1:]
startBlock, err := strconv.ParseUint(startBlockRaw, 10, 64)
if err != nil {
return nil, fmt.Errorf("failed to parse provided start block %s: %w", startBlockRaw, err)
}
trackerStartBlocksConfig[address] = startBlock
}
return trackerStartBlocksConfig, nil
}
// parseBurnContractInfo parses provided burn contract information and returns burn contract block and address
func parseBurnContractInfo(burnContractInfoRaw string) (*polybft.BurnContractInfo, error) {
// <block>:<address>[:<burn destination address>]
burnContractParts := strings.Split(burnContractInfoRaw, ":")
if len(burnContractParts) < 2 || len(burnContractParts) > 3 {
return nil, fmt.Errorf("expected format: <block>:<address>[:<burn destination>]")
}
blockRaw := burnContractParts[0]
blockNum, err := types.ParseUint64orHex(&blockRaw)
if err != nil {
return nil, fmt.Errorf("failed to parse block number %s: %w", blockRaw, err)
}
contractAddress := burnContractParts[1]
if err = types.IsValidAddress(contractAddress); err != nil {
return nil, fmt.Errorf("failed to parse contract address %s: %w", contractAddress, err)
}
if len(burnContractParts) == 2 {
return &polybft.BurnContractInfo{
BlockNumber: blockNum,
Address: types.StringToAddress(contractAddress),
DestinationAddress: types.ZeroAddress,
}, nil
}
destinationAddress := burnContractParts[2]
if err = types.IsValidAddress(destinationAddress); err != nil {
return nil, fmt.Errorf("failed to parse burn destination address %s: %w", destinationAddress, err)
}
return &polybft.BurnContractInfo{
BlockNumber: blockNum,
Address: types.StringToAddress(contractAddress),
DestinationAddress: types.StringToAddress(destinationAddress),
}, nil
}
// GetValidatorKeyFiles returns file names which has validator secrets
func GetValidatorKeyFiles(rootDir, filePrefix string) ([]string, error) {
if rootDir == "" {
rootDir = "."
}
files, err := ioutil.ReadDir(rootDir)
if err != nil {
return nil, err
}
matchedFiles := 0
fileNames := make([]string, len(files))
for _, file := range files {
fileName := file.Name()
if file.IsDir() && strings.HasPrefix(fileName, filePrefix) {
fileNames[matchedFiles] = fileName
matchedFiles++
}
}
// reslice to remove empty entries
fileNames = fileNames[:matchedFiles]
// we must sort files by number after the prefix not by name string
sort.Slice(fileNames, func(i, j int) bool {
first := strings.TrimPrefix(fileNames[i], filePrefix)
second := strings.TrimPrefix(fileNames[j], filePrefix)
num1, _ := strconv.Atoi(strings.TrimLeft(first, "-"))
num2, _ := strconv.Atoi(strings.TrimLeft(second, "-"))
return num1 < num2
})
return fileNames, nil
}
// ReadValidatorsByPrefix reads validators secrets on a given root directory and with given folder prefix
func ReadValidatorsByPrefix(dir, prefix string) ([]*validator.GenesisValidator, error) {
validatorKeyFiles, err := GetValidatorKeyFiles(dir, prefix)
if err != nil {
return nil, err
}
validators := make([]*validator.GenesisValidator, len(validatorKeyFiles))
for i, file := range validatorKeyFiles {
path := filepath.Join(dir, file)
account, nodeID, err := getSecrets(path)
if err != nil {
return nil, err
}
validators[i] = &validator.GenesisValidator{
Address: types.Address(account.Ecdsa.Address()),
BlsKey: hex.EncodeToString(account.Bls.PublicKey().Marshal()),
MultiAddr: fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", "127.0.0.1", bootnodePortStart+int64(i), nodeID),
Stake: big.NewInt(0),
}
}
return validators, nil
}
func getSecrets(directory string) (*wallet.Account, string, error) {
baseConfig := &secrets.SecretsManagerParams{
Logger: hclog.NewNullLogger(),
Extra: map[string]interface{}{
secrets.Path: directory,
},
}
localManager, err := local.SecretsManagerFactory(nil, baseConfig)
if err != nil {
return nil, "", fmt.Errorf("unable to instantiate local secrets manager, %w", err)
}
nodeID, err := helper.LoadNodeID(localManager)
if err != nil {
return nil, "", err
}
account, err := wallet.NewAccountFromSecret(localManager)
if err != nil {
return nil, "", err
}
return account, nodeID, err
}
// GenerateExtraDataPolyBft populates Extra with specific fields required for polybft consensus protocol
func GenerateExtraDataPolyBft(validators []*validator.ValidatorMetadata) ([]byte, error) {
delta := &validator.ValidatorSetDelta{
Added: validators,
Removed: bitmap.Bitmap{},
}
extra := polybft.Extra{Validators: delta, Checkpoint: &polybft.CheckpointData{}}
return extra.MarshalRLPTo(nil), nil
}