-
Notifications
You must be signed in to change notification settings - Fork 16
/
apputils.go
191 lines (179 loc) · 6.17 KB
/
apputils.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
package vochain
import (
"encoding/hex"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"time"
"go.vocdoni.io/dvote/crypto/ethereum"
"go.vocdoni.io/dvote/util"
"go.vocdoni.io/dvote/vochain/genesis"
"go.vocdoni.io/proto/build/go/models"
"google.golang.org/protobuf/proto"
"github.com/cometbft/cometbft/crypto"
crypto25519 "github.com/cometbft/cometbft/crypto/ed25519"
crypto256k1 "github.com/cometbft/cometbft/crypto/secp256k1"
tmp2p "github.com/cometbft/cometbft/p2p"
"github.com/cometbft/cometbft/privval"
tmtypes "github.com/cometbft/cometbft/types"
ethcommon "github.com/ethereum/go-ethereum/common"
)
// NewPrivateValidator returns a tendermint file private validator (key and state)
// if tmPrivKey not specified, uses the existing one or generates a new one
func NewPrivateValidator(tmPrivKey, keyFilePath, stateFilePath string) (*privval.FilePV, error) {
pv := privval.LoadOrGenFilePV(keyFilePath, stateFilePath)
if len(tmPrivKey) > 0 {
var privKey crypto256k1.PrivKey
keyBytes, err := hex.DecodeString(util.TrimHex(tmPrivKey))
if err != nil {
return nil, fmt.Errorf("cannot decode private key: (%s)", err)
}
privKey = make([]byte, crypto256k1.PrivKeySize)
if n := copy(privKey[:], keyBytes); n != crypto256k1.PrivKeySize {
return nil, fmt.Errorf("incorrect private key length (got %d, need %d)", n, crypto25519.PrivateKeySize)
}
pv.Key.Address = privKey.PubKey().Address()
pv.Key.PrivKey = privKey
pv.Key.PubKey = privKey.PubKey()
}
return pv, nil
}
// NewNodeKey returns and saves to the disk storage a tendermint node key.
// If tmPrivKey not specified, generates a new one
func NewNodeKey(tmPrivKey, nodeKeyFilePath string) (*tmp2p.NodeKey, error) {
nodeKey := &tmp2p.NodeKey{}
if tmPrivKey != "" {
keyBytes, err := hex.DecodeString(util.TrimHex(tmPrivKey))
if err != nil {
return nil, fmt.Errorf("cannot decode private key: (%s)", err)
}
// We need to use ed25519 curve for node key since tendermint does not support secp256k1
nodeKey.PrivKey = crypto25519.PrivKey(keyBytes)
} else {
nodeKey.PrivKey = crypto25519.GenPrivKey()
}
// Write nodeKey to disk
return nodeKey, nodeKey.SaveAs(nodeKeyFilePath)
}
// NodeKeyToAddress returns the ethereum address of the given cometBFT node key
func NodePvKeyToAddress(pubk crypto.PubKey) (ethcommon.Address, error) {
return ethereum.AddrFromPublicKey(pubk.Bytes())
}
// GenerateFaucetPackage generates a faucet package.
// The package is signed by the given `from` key (holder of the funds) and sent to the `to` address.
// The `amount` is the amount of tokens to be sent.
func GenerateFaucetPackage(from *ethereum.SignKeys, to ethcommon.Address, amount uint64) (*models.FaucetPackage, error) {
nonce := util.RandomInt(0, math.MaxInt32)
payload := &models.FaucetPayload{
Identifier: uint64(nonce),
To: to.Bytes(),
Amount: amount,
}
payloadBytes, err := proto.Marshal(payload)
if err != nil {
return nil, err
}
payloadSignature, err := from.SignEthereum(payloadBytes)
if err != nil {
return nil, err
}
return &models.FaucetPackage{
Payload: payloadBytes,
Signature: payloadSignature,
}, nil
}
// NewTemplateGenesisFile creates a genesis file with the given number of validators and its private keys.
// Also includes faucet account.
// The genesis document is returned.
func NewTemplateGenesisFile(dir string, validators int) (*tmtypes.GenesisDoc, error) {
gd := tmtypes.GenesisDoc{}
gd.ChainID = "test-chain-1"
gd.GenesisTime = time.Now()
gd.InitialHeight = 0
gd.ConsensusParams = tmtypes.DefaultConsensusParams()
gd.ConsensusParams.Block.MaxBytes = 5242880
gd.ConsensusParams.Block.MaxGas = -1
gd.ConsensusParams.Evidence.MaxAgeNumBlocks = 100000
gd.ConsensusParams.Evidence.MaxAgeDuration = 10000
gd.ConsensusParams.Validator.PubKeyTypes = []string{"secp256k1"}
// Create validators
appStateValidators := []genesis.AppStateValidators{}
for i := 0; i < validators; i++ {
nodeDir := filepath.Join(dir, fmt.Sprintf("node%d", i))
if err := os.MkdirAll(nodeDir, 0o700); err != nil {
return nil, err
}
pk := crypto256k1.GenPrivKey()
privKeyHex := hex.EncodeToString(pk.Bytes())
pv, err := NewPrivateValidator(privKeyHex,
filepath.Join(nodeDir, "priv_validator_key.json"),
filepath.Join(nodeDir, "priv_validator_state.json"),
)
if err != nil {
return nil, fmt.Errorf("cannot create validator key and state: (%v)", err)
}
pv.Save()
if err := os.WriteFile(filepath.Join(nodeDir, "hex_priv_key"), []byte(privKeyHex), 0o600); err != nil {
return nil, err
}
signer := ethereum.SignKeys{}
if err := signer.AddHexKey(hex.EncodeToString(pv.Key.PrivKey.Bytes())); err != nil {
return nil, err
}
appStateValidators = append(appStateValidators, genesis.AppStateValidators{
Address: signer.Address().Bytes(),
PubKey: pv.Key.PubKey.Bytes(),
Power: 10,
KeyIndex: uint8(i + 1), // zero is reserved for disabling validator key keeper capabilities
})
}
// Faucet
faucet := ethereum.SignKeys{}
if err := faucet.Generate(); err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(dir, "faucet_hex_key"),
[]byte(fmt.Sprintf("%x", faucet.PrivateKey())), 0o600); err != nil {
return nil, err
}
// Create seed node
seedDir := filepath.Join(dir, "seed")
if err := os.MkdirAll(seedDir, 0o700); err != nil {
return nil, err
}
seedNodeKey, err := NewNodeKey("", filepath.Join(seedDir, "node_key.json"))
if err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(
seedDir, "seed_address"),
[]byte(fmt.Sprintf("%s@seed1.foo.bar:26656", seedNodeKey.ID())),
0o600); err != nil {
return nil, err
}
if err := os.WriteFile(filepath.Join(seedDir, "hex_seed_key"),
[]byte(hex.EncodeToString(seedNodeKey.PrivKey.Bytes())),
0o600); err != nil {
return nil, err
}
// Build genesis app state and create genesis file
appState := genesis.AppState{
Validators: appStateValidators,
Accounts: []genesis.Account{
{
Address: faucet.Address().Bytes(),
Balance: 100000,
},
},
TxCost: genesis.TransactionCosts{},
}
appState.MaxElectionSize = 100000
appStateBytes, err := json.Marshal(appState)
if err != nil {
return nil, err
}
gd.AppState = appStateBytes
return &gd, gd.SaveAs(filepath.Join(dir, "genesis.json"))
}