-
Notifications
You must be signed in to change notification settings - Fork 0
/
export_operation.go
363 lines (318 loc) · 10.1 KB
/
export_operation.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
package evm
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
ethcmn "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
sdk "github.com/evoblockchain/evochain/libs/cosmos-sdk/types"
"github.com/evoblockchain/evochain/libs/tendermint/libs/log"
dbm "github.com/evoblockchain/evochain/libs/tm-db"
"github.com/evoblockchain/evochain/x/evm/types"
)
const (
codeFileSuffix = ".code"
storageFileSuffix = ".storage"
codeSubPath = "code"
storageSubPath = "storage"
defaultMode = "default"
filesMode = "files"
dbMode = "db"
)
var (
codePath string
storagePath string
defaultPath, _ = os.Getwd()
goroutinePool chan struct{}
wg sync.WaitGroup
codeCount uint64
storageCount uint64
evmByteCodeDB, evmStateDB dbm.DB
)
// initExportEnv only initializes the paths and goroutine pool
func initExportEnv(dataPath, mode string, goroutineNum uint64) {
if dataPath == "" {
dataPath = defaultPath
}
switch mode {
case "default":
return
case "files":
codePath = filepath.Join(dataPath, codeSubPath)
storagePath = filepath.Join(dataPath, storageSubPath)
err := os.MkdirAll(codePath, 0777)
if err != nil {
panic(err)
}
err = os.MkdirAll(storagePath, 0777)
if err != nil {
panic(err)
}
initGoroutinePool(goroutineNum)
case "db":
initEVMDB(dataPath)
initGoroutinePool(goroutineNum)
default:
panic("unsupported export mode")
}
}
// initImportEnv only initializes the paths and goroutine pool
func initImportEnv(dataPath, mode string, goroutineNum uint64) {
if dataPath == "" {
dataPath = defaultPath
}
switch mode {
case "default":
return
case "files":
codePath = filepath.Join(dataPath, codeSubPath)
storagePath = filepath.Join(dataPath, storageSubPath)
initGoroutinePool(goroutineNum)
case "db":
initEVMDB(dataPath)
default:
panic("unsupported import mode")
}
}
// exportToFile export EVM code and storage to files
func exportToFile(ctx sdk.Context, k Keeper, address ethcmn.Address) {
// write Code
addGoroutine()
go syncWriteAccountCode(ctx, k, address)
// write Storage
addGoroutine()
go syncWriteAccountStorage(ctx, k, address)
}
// importFromFile import EVM code and storage from files
func importFromFile(ctx sdk.Context, logger log.Logger, k Keeper, address ethcmn.Address, codeHash []byte) {
// read Code from file
addGoroutine()
go syncReadCodeFromFile(ctx, logger, k, address, codeHash)
// read Storage From file
addGoroutine()
go syncReadStorageFromFile(ctx, logger, k, address)
}
// exportToDB export EVM code and storage to leveldb
func exportToDB(ctx sdk.Context, k Keeper, address ethcmn.Address, codeHash []byte) {
if code := k.GetCode(ctx, address); len(code) > 0 {
// TODO repeat code
if err := evmByteCodeDB.Set(append(types.KeyPrefixCode, codeHash...), code); err != nil {
panic(err)
}
codeCount++
}
addGoroutine()
go exportStorage(ctx, k, address, evmStateDB)
}
// importFromDB import EVM code and storage to leveldb
func importFromDB(ctx sdk.Context, k Keeper, address ethcmn.Address, codeHash []byte) {
if isEmptyState(evmByteCodeDB) || isEmptyState(evmStateDB) {
panic("failed to open evm db")
}
code, err := evmByteCodeDB.Get(append(types.KeyPrefixCode, codeHash...))
if err != nil {
panic(err)
}
if len(code) != 0 {
k.SetCodeDirectly(ctx, codeHash, code)
codeCount++
}
prefix := types.AddressStoragePrefix(address)
iterator, err := evmStateDB.Iterator(prefix, sdk.PrefixEndBytes(prefix))
if err != nil {
panic(err)
}
for ; iterator.Valid(); iterator.Next() {
k.SetStateDirectly(ctx, address, ethcmn.BytesToHash(iterator.Key()[len(prefix):]), ethcmn.BytesToHash(iterator.Value()))
storageCount++
}
iterator.Close()
}
func exportStorage(ctx sdk.Context, k Keeper, addr ethcmn.Address, db dbm.DB) {
defer finishGoroutine()
prefix := types.AddressStoragePrefix(addr)
err := k.ForEachStorage(ctx, addr, func(key, value ethcmn.Hash) bool {
db.Set(append(prefix, key.Bytes()...), value.Bytes())
atomic.AddUint64(&storageCount, 1)
return false
})
if err != nil {
panic(err)
}
}
func initEVMDB(path string) {
var err error
evmByteCodeDB, err = sdk.NewDB("evm_bytecode", path)
if err != nil {
panic(err)
}
evmStateDB, err = sdk.NewDB("evm_state", path)
if err != nil {
panic(err)
}
}
// initGoroutinePool creates an appropriate number of maximum goroutine
func initGoroutinePool(goroutineNum uint64) {
if goroutineNum == 0 {
goroutineNum = uint64(runtime.NumCPU()-1) * 16
}
goroutinePool = make(chan struct{}, goroutineNum)
}
// addGoroutine if goroutinePool is not full, then create a goroutine
func addGoroutine() {
goroutinePool <- struct{}{}
wg.Add(1)
}
// finishGoroutine follows the function addGoroutine
func finishGoroutine() {
<-goroutinePool
wg.Done()
}
// createFile creates a file based on a absolute path
func createFile(filePath string) *os.File {
file, err := os.Create(filePath)
if err != nil {
panic(err)
}
return file
}
// closeFile closes the current file and writer, in case of the waste of memory
func closeFile(writer *bufio.Writer, file *os.File) {
err := writer.Flush()
if err != nil {
panic(err)
}
err = file.Close()
if err != nil {
panic(err)
}
}
// writeOneLine only writes data into one line
func writeOneLine(writer *bufio.Writer, data string) {
_, err := writer.WriteString(data)
if err != nil {
panic(err)
}
}
// ************************************************************************************************************
// the List of functions are used for writing different type of data into files
// First, get data from cache or db
// Second, format data, then write them into file
// note: there is no way of adding log when ExportGenesis, because it will generate many logs in genesis.json
// ************************************************************************************************************
// syncWriteAccountCode synchronize the process of writing types.Code into individual file.
// It doesn't create file when there is no code linked to an account
func syncWriteAccountCode(ctx sdk.Context, k Keeper, address ethcmn.Address) {
defer finishGoroutine()
code := k.GetCode(ctx, address)
if len(code) != 0 {
file := createFile(filepath.Join(codePath, address.String()+codeFileSuffix))
writer := bufio.NewWriter(file)
defer closeFile(writer, file)
writeOneLine(writer, hexutil.Bytes(code).String())
atomic.AddUint64(&codeCount, 1)
}
}
// syncWriteAccountStorage synchronize the process of writing types.Storage into individual file
// It will delete the file when there is no storage linked to a contract
func syncWriteAccountStorage(ctx sdk.Context, k Keeper, address ethcmn.Address) {
defer finishGoroutine()
filename := filepath.Join(storagePath, address.String()+storageFileSuffix)
index := 0
defer func() {
if index == 0 { // make a judgement that there is a slice of ethtypes.State or not
if err := os.Remove(filename); err != nil {
panic(err)
}
} else {
atomic.AddUint64(&storageCount, uint64(index))
}
}()
file := createFile(filename)
writer := bufio.NewWriter(file)
defer closeFile(writer, file)
// call this function, used for iterating all the key&value based on an address
err := k.ForEachStorage(ctx, address, func(key, value ethcmn.Hash) bool {
writeOneLine(writer, fmt.Sprintf("%s:%s\n", key.Hex(), value.Hex()))
index++
return false
})
if err != nil {
panic(err)
}
}
// ************************************************************************************************************
// the List of functions are used for loading different type of data, then persists data on db
// First, get data from local file
// Second, format data, then set them into db
// ************************************************************************************************************
// syncReadCodeFromFile synchronize the process of setting types.Code into evm db when InitGenesis
func syncReadCodeFromFile(ctx sdk.Context, logger log.Logger, k Keeper, address ethcmn.Address, codeHash []byte) {
defer finishGoroutine()
codeFilePath := filepath.Join(codePath, address.String()+codeFileSuffix)
if pathExist(codeFilePath) {
logger.Debug("start loading code", "filename", address.String()+codeFileSuffix)
bin, err := ioutil.ReadFile(codeFilePath)
if err != nil {
panic(err)
}
// make "0x608002412.....80" string into a slice of byte
code := hexutil.MustDecode(string(bin))
// Set contract code into db, ignoring setting in cache
k.SetCodeDirectly(ctx, codeHash, code)
atomic.AddUint64(&codeCount, 1)
}
}
// syncReadStorageFromFile synchronize the process of setting types.Storage into evm db when InitGenesis
func syncReadStorageFromFile(ctx sdk.Context, logger log.Logger, k Keeper, address ethcmn.Address) {
defer finishGoroutine()
storageFilePath := filepath.Join(storagePath, address.String()+storageFileSuffix)
if pathExist(storageFilePath) {
logger.Debug("start loading storage", "filename", address.String()+storageFileSuffix)
f, err := os.Open(storageFilePath)
if err != nil {
panic(err)
}
defer f.Close()
rd := bufio.NewReader(f)
for {
// eg. kvStr = "0xc543bf77d2a7bddbeb14b8d8bfa3405a8410be06d8c3e68d5bd5e7b9abd43d39:0x4e584d0000000000000000000000000000000000000000000000000000000006\n"
kvStr, err := rd.ReadString('\n')
if err != nil || io.EOF == err {
break
}
// remove '\n' in the end of string, then split kvStr based on ':'
kvPair := strings.Split(strings.ReplaceAll(kvStr, "\n", ""), ":")
//convert hexStr into common.Hash struct
key, value := ethcmn.HexToHash(kvPair[0]), ethcmn.HexToHash(kvPair[1])
// Set the state of key&value into db, ignoring setting in cache
k.SetStateDirectly(ctx, address, key, value)
atomic.AddUint64(&storageCount, 1)
}
}
}
// pathExist used for judging the file or path exist or not when InitGenesis
func pathExist(path string) bool {
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func isEmptyState(db dbm.DB) bool {
return db.Stats()["leveldb.sstables"] == ""
}
func CloseDB() {
evmByteCodeDB.Close()
evmStateDB.Close()
}