-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
executable file
·373 lines (296 loc) · 9.67 KB
/
chain.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package chain
import (
"encoding/binary"
"encoding/json"
"fmt"
"math/big"
"os"
"github.com/definenulls/komerco-chain/helper/hex"
"github.com/definenulls/komerco-chain/types"
"github.com/hashicorp/go-multierror"
)
var (
// GenesisGasLimit is the default gas limit of the Genesis block.
GenesisGasLimit uint64 = 4712388
// GenesisDifficulty is the default difficulty of the Genesis block.
GenesisDifficulty = big.NewInt(131072)
)
// Chain is the blockchain chain configuration
type Chain struct {
Name string `json:"name"`
Genesis *Genesis `json:"genesis"`
Params *Params `json:"params"`
Bootnodes []string `json:"bootnodes,omitempty"`
}
// Genesis specifies the header fields, state of a genesis block
type Genesis struct {
Config *Params `json:"config"`
Nonce [8]byte `json:"nonce"`
Timestamp uint64 `json:"timestamp"`
ExtraData []byte `json:"extraData,omitempty"`
GasLimit uint64 `json:"gasLimit"`
Difficulty uint64 `json:"difficulty"`
Mixhash types.Hash `json:"mixHash"`
Coinbase types.Address `json:"coinbase"`
Alloc map[types.Address]*GenesisAccount `json:"alloc,omitempty"`
// Override
StateRoot types.Hash
// Only for testing
Number uint64 `json:"number"`
GasUsed uint64 `json:"gasUsed"`
ParentHash types.Hash `json:"parentHash"`
}
// GenesisHeader converts the initially defined genesis struct to a header
func (g *Genesis) GenesisHeader() *types.Header {
stateRoot := types.EmptyRootHash
if g.StateRoot != types.ZeroHash {
stateRoot = g.StateRoot
}
head := &types.Header{
Number: g.Number,
Nonce: g.Nonce,
Timestamp: g.Timestamp,
ParentHash: g.ParentHash,
ExtraData: g.ExtraData,
GasLimit: g.GasLimit,
GasUsed: g.GasUsed,
Difficulty: g.Difficulty,
MixHash: g.Mixhash,
Miner: g.Coinbase.Bytes(),
StateRoot: stateRoot,
Sha3Uncles: types.EmptyUncleHash,
ReceiptsRoot: types.EmptyRootHash,
TxRoot: types.EmptyRootHash,
}
// Set default values if none are passed in
if g.GasLimit == 0 {
head.GasLimit = GenesisGasLimit
}
if g.Difficulty == 0 {
head.Difficulty = GenesisDifficulty.Uint64()
}
return head
}
// Hash computes the genesis hash
func (g *Genesis) Hash() types.Hash {
header := g.GenesisHeader()
header.ComputeHash()
return header.Hash
}
// MarshalJSON implements the json interface
func (g *Genesis) MarshalJSON() ([]byte, error) {
type Genesis struct {
Nonce string `json:"nonce"`
Timestamp *string `json:"timestamp,omitempty"`
ExtraData *string `json:"extraData,omitempty"`
GasLimit *string `json:"gasLimit,omitempty"`
Difficulty *string `json:"difficulty,omitempty"`
Mixhash types.Hash `json:"mixHash"`
Coinbase types.Address `json:"coinbase"`
Alloc *map[string]*GenesisAccount `json:"alloc,omitempty"`
Number *string `json:"number,omitempty"`
GasUsed *string `json:"gasUsed,omitempty"`
ParentHash types.Hash `json:"parentHash"`
}
var enc Genesis
enc.Nonce = hex.EncodeToHex(g.Nonce[:])
enc.Timestamp = types.EncodeUint64(g.Timestamp)
enc.ExtraData = types.EncodeBytes(g.ExtraData)
enc.GasLimit = types.EncodeUint64(g.GasLimit)
enc.Difficulty = types.EncodeUint64(g.Difficulty)
enc.Mixhash = g.Mixhash
enc.Coinbase = g.Coinbase
if g.Alloc != nil {
alloc := make(map[string]*GenesisAccount, len(g.Alloc))
for k, v := range g.Alloc {
alloc[k.String()] = v
}
enc.Alloc = &alloc
}
enc.Number = types.EncodeUint64(g.Number)
enc.GasUsed = types.EncodeUint64(g.GasUsed)
enc.ParentHash = g.ParentHash
return json.Marshal(&enc)
}
// UnmarshalJSON implements the json interface
func (g *Genesis) UnmarshalJSON(data []byte) error {
type Genesis struct {
Nonce *string `json:"nonce"`
Timestamp *string `json:"timestamp"`
ExtraData *string `json:"extraData"`
GasLimit *string `json:"gasLimit"`
Difficulty *string `json:"difficulty"`
Mixhash *types.Hash `json:"mixHash"`
Coinbase *types.Address `json:"coinbase"`
Alloc map[string]*GenesisAccount `json:"alloc"`
Number *string `json:"number"`
GasUsed *string `json:"gasUsed"`
ParentHash *types.Hash `json:"parentHash"`
}
var dec Genesis
if err := json.Unmarshal(data, &dec); err != nil {
return err
}
var err, subErr error
parseError := func(field string, subErr error) {
err = multierror.Append(err, fmt.Errorf("%s: %w", field, subErr))
}
nonce, subErr := types.ParseUint64orHex(dec.Nonce)
if subErr != nil {
parseError("nonce", subErr)
}
binary.BigEndian.PutUint64(g.Nonce[:], nonce)
g.Timestamp, subErr = types.ParseUint64orHex(dec.Timestamp)
if subErr != nil {
parseError("timestamp", subErr)
}
if dec.ExtraData != nil {
g.ExtraData, subErr = types.ParseBytes(dec.ExtraData)
if subErr != nil {
parseError("extradata", subErr)
}
}
if dec.GasLimit == nil {
return fmt.Errorf("field 'gaslimit' is required")
}
g.GasLimit, subErr = types.ParseUint64orHex(dec.GasLimit)
if subErr != nil {
parseError("gaslimit", subErr)
}
g.Difficulty, subErr = types.ParseUint64orHex(dec.Difficulty)
if subErr != nil {
parseError("difficulty", subErr)
}
if dec.Mixhash != nil {
g.Mixhash = *dec.Mixhash
}
if dec.Coinbase != nil {
g.Coinbase = *dec.Coinbase
}
if dec.Alloc != nil {
g.Alloc = make(map[types.Address]*GenesisAccount, len(dec.Alloc))
for k, v := range dec.Alloc {
g.Alloc[types.StringToAddress(k)] = v
}
}
g.Number, subErr = types.ParseUint64orHex(dec.Number)
if subErr != nil {
parseError("number", subErr)
}
g.GasUsed, subErr = types.ParseUint64orHex(dec.GasUsed)
if subErr != nil {
parseError("gasused", subErr)
}
if dec.ParentHash != nil {
g.ParentHash = *dec.ParentHash
}
return err
}
// Genesis alloc
// GenesisAccount is an account in the state of the genesis block.
type GenesisAccount struct {
Code []byte `json:"code,omitempty"`
Storage map[types.Hash]types.Hash `json:"storage,omitempty"`
Balance *big.Int `json:"balance,omitempty"`
Nonce uint64 `json:"nonce,omitempty"`
PrivateKey []byte `json:"secretKey,omitempty"` // for tests
}
type genesisAccountEncoder struct {
Code *string `json:"code,omitempty"`
Storage map[types.Hash]types.Hash `json:"storage,omitempty"`
Balance *string `json:"balance"`
Nonce *string `json:"nonce,omitempty"`
PrivateKey *string `json:"secretKey,omitempty"`
}
// ENCODING //
func (g *GenesisAccount) MarshalJSON() ([]byte, error) {
obj := &genesisAccountEncoder{}
if g.Code != nil {
obj.Code = types.EncodeBytes(g.Code)
}
if len(g.Storage) != 0 {
obj.Storage = g.Storage
}
if g.Balance != nil {
obj.Balance = types.EncodeBigInt(g.Balance)
}
if g.Nonce != 0 {
obj.Nonce = types.EncodeUint64(g.Nonce)
}
if g.PrivateKey != nil {
obj.PrivateKey = types.EncodeBytes(g.PrivateKey)
}
return json.Marshal(obj)
}
// DECODING //
func (g *GenesisAccount) UnmarshalJSON(data []byte) error {
type GenesisAccount struct {
Code *string `json:"code,omitempty"`
Storage map[types.Hash]types.Hash `json:"storage,omitempty"`
Balance *string `json:"balance"`
Nonce *string `json:"nonce,omitempty"`
PrivateKey *string `json:"secretKey,omitempty"`
}
var dec GenesisAccount
if err := json.Unmarshal(data, &dec); err != nil {
return err
}
var err error
var subErr error
parseError := func(field string, subErr error) {
err = multierror.Append(err, fmt.Errorf("%s: %w", field, subErr))
}
if dec.Code != nil {
g.Code, subErr = types.ParseBytes(dec.Code)
if subErr != nil {
parseError("code", subErr)
}
}
if dec.Storage != nil {
g.Storage = dec.Storage
}
g.Balance, subErr = types.ParseUint256orHex(dec.Balance)
if subErr != nil {
parseError("balance", subErr)
}
g.Nonce, subErr = types.ParseUint64orHex(dec.Nonce)
if subErr != nil {
parseError("nonce", subErr)
}
if dec.PrivateKey != nil {
g.PrivateKey, subErr = types.ParseBytes(dec.PrivateKey)
if subErr != nil {
parseError("privatekey", subErr)
}
}
return err
}
func Import(chain string) (*Chain, error) {
return ImportFromFile(chain)
}
// ImportFromFile imports a chain from a filepath
func ImportFromFile(filename string) (*Chain, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
return importChain(data)
}
func importChain(content []byte) (*Chain, error) {
var chain *Chain
if err := json.Unmarshal(content, &chain); err != nil {
return nil, err
}
if engines := chain.Params.Engine; len(engines) != 1 {
return nil, fmt.Errorf("expected one consensus engine but found %d", len(engines))
}
return chain, nil
}
// GetGenesisAccountBalance returns balance for genesis account based on its address (expressed in weis).
// If not found in provided allocations map, 0 is returned.
func GetGenesisAccountBalance(address types.Address, allocations map[types.Address]*GenesisAccount) (*big.Int, error) {
if genesisAcc, ok := allocations[address]; ok {
return genesisAcc.Balance, nil
}
return nil, fmt.Errorf("genesis account %s is not found among genesis allocations", address)
}