-
Notifications
You must be signed in to change notification settings - Fork 704
/
Copy pathgenesis.go
195 lines (172 loc) · 6.47 KB
/
genesis.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package tmpnet
import (
"encoding/json"
"errors"
"fmt"
"math/big"
"time"
"github.com/ava-labs/coreth/core"
"github.com/ava-labs/coreth/params"
"github.com/ava-labs/coreth/plugin/evm"
"github.com/ava-labs/avalanchego/genesis"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/upgrade"
"github.com/ava-labs/avalanchego/utils/constants"
"github.com/ava-labs/avalanchego/utils/crypto/secp256k1"
"github.com/ava-labs/avalanchego/utils/formatting/address"
"github.com/ava-labs/avalanchego/utils/units"
"github.com/ava-labs/avalanchego/vms/platformvm/reward"
)
const (
defaultGasLimit = uint64(100_000_000) // Gas limit is arbitrary
// Arbitrarily large amount of AVAX to fund keys on the X-Chain for testing
defaultFundedKeyXChainAmount = 30 * units.MegaAvax
)
var (
// Arbitrarily large amount of AVAX (10^12) to fund keys on the C-Chain for testing
defaultFundedKeyCChainAmount = new(big.Int).Exp(big.NewInt(10), big.NewInt(30), nil)
errNoKeysForGenesis = errors.New("no keys to fund for genesis")
errInvalidNetworkIDForGenesis = errors.New("network ID can't be mainnet, testnet or local network ID for genesis")
errMissingStakersForGenesis = errors.New("no stakers provided for genesis")
)
// Helper type to simplify configuring X-Chain genesis balances
type XChainBalanceMap map[ids.ShortID]uint64
// Create a genesis struct valid for bootstrapping a test
// network. Note that many of the genesis fields (e.g. reward
// addresses) are randomly generated or hard-coded.
func NewTestGenesis(
networkID uint32,
nodes []*Node,
keysToFund []*secp256k1.PrivateKey,
) (*genesis.UnparsedConfig, error) {
// Validate inputs
switch networkID {
case constants.TestnetID, constants.MainnetID, constants.LocalID:
return nil, errInvalidNetworkIDForGenesis
}
if len(nodes) == 0 {
return nil, errMissingStakersForGenesis
}
if len(keysToFund) == 0 {
return nil, errNoKeysForGenesis
}
initialStakers, err := stakersForNodes(networkID, nodes)
if err != nil {
return nil, fmt.Errorf("failed to configure stakers for nodes: %w", err)
}
// Address that controls stake doesn't matter -- generate it randomly
stakeAddress, err := address.Format(
"X",
constants.GetHRP(networkID),
ids.GenerateTestShortID().Bytes(),
)
if err != nil {
return nil, fmt.Errorf("failed to format stake address: %w", err)
}
// Ensure the total stake allows a MegaAvax per staker
totalStake := uint64(len(initialStakers)) * units.MegaAvax
// The eth address is only needed to link pre-mainnet assets. Until that capability
// becomes necessary for testing, use a bogus address.
//
// Reference: https://github.com/ava-labs/avalanchego/issues/1365#issuecomment-1511508767
ethAddress := "0x0000000000000000000000000000000000000000"
now := time.Now()
config := &genesis.UnparsedConfig{
NetworkID: networkID,
Allocations: []genesis.UnparsedAllocation{
{
ETHAddr: ethAddress,
AVAXAddr: stakeAddress,
InitialAmount: 0,
UnlockSchedule: []genesis.LockedAmount{ // Provides stake to validators
{
Amount: totalStake,
Locktime: uint64(now.Add(7 * 24 * time.Hour).Unix()), // 1 Week
},
},
},
},
StartTime: uint64(now.Unix()),
InitialStakedFunds: []string{stakeAddress},
InitialStakeDuration: 365 * 24 * 60 * 60, // 1 year
InitialStakeDurationOffset: 90 * 60, // 90 minutes
Message: "hello avalanche!",
InitialStakers: initialStakers,
}
// Ensure pre-funded keys have arbitrary large balances on both chains to support testing
xChainBalances := make(XChainBalanceMap, len(keysToFund))
cChainBalances := make(core.GenesisAlloc, len(keysToFund))
for _, key := range keysToFund {
xChainBalances[key.Address()] = defaultFundedKeyXChainAmount
cChainBalances[evm.GetEthAddress(key)] = core.GenesisAccount{
Balance: defaultFundedKeyCChainAmount,
}
}
// Set X-Chain balances
for xChainAddress, balance := range xChainBalances {
avaxAddr, err := address.Format("X", constants.GetHRP(networkID), xChainAddress[:])
if err != nil {
return nil, fmt.Errorf("failed to format X-Chain address: %w", err)
}
config.Allocations = append(
config.Allocations,
genesis.UnparsedAllocation{
ETHAddr: ethAddress,
AVAXAddr: avaxAddr,
InitialAmount: balance,
UnlockSchedule: []genesis.LockedAmount{
{
Amount: 20 * units.MegaAvax,
},
{
Amount: totalStake,
Locktime: uint64(now.Add(7 * 24 * time.Hour).Unix()), // 1 Week
},
},
},
)
}
chainID := big.NewInt(int64(networkID))
// Define C-Chain genesis
cChainGenesis := &core.Genesis{
// TODO: remove this after Etna and set only the chainID
Config: params.GetChainConfig(upgrade.Default, chainID), // upgrade will be again set by VM according to the snow.Context
Difficulty: big.NewInt(0), // Difficulty is a mandatory field
Timestamp: uint64(upgrade.InitiallyActiveTime.Unix()), // This time enables Avalanche upgrades by default
GasLimit: defaultGasLimit,
Alloc: cChainBalances,
}
cChainGenesisBytes, err := json.Marshal(cChainGenesis)
if err != nil {
return nil, fmt.Errorf("failed to marshal C-Chain genesis: %w", err)
}
config.CChainGenesis = string(cChainGenesisBytes)
return config, nil
}
// Returns staker configuration for the given set of nodes.
func stakersForNodes(networkID uint32, nodes []*Node) ([]genesis.UnparsedStaker, error) {
// Give staking rewards for initial validators to a random address. Any testing of staking rewards
// will be easier to perform with nodes other than the initial validators since the timing of
// staking can be more easily controlled.
rewardAddr, err := address.Format("X", constants.GetHRP(networkID), ids.GenerateTestShortID().Bytes())
if err != nil {
return nil, fmt.Errorf("failed to format reward address: %w", err)
}
// Configure provided nodes as initial stakers
initialStakers := make([]genesis.UnparsedStaker, len(nodes))
for i, node := range nodes {
pop, err := node.GetProofOfPossession()
if err != nil {
return nil, fmt.Errorf("failed to derive proof of possession for node %s: %w", node.NodeID, err)
}
initialStakers[i] = genesis.UnparsedStaker{
NodeID: node.NodeID,
RewardAddress: rewardAddr,
DelegationFee: .01 * reward.PercentDenominator,
Signer: pop,
}
}
return initialStakers, nil
}