/
database_upgrade.go
499 lines (460 loc) · 13.2 KB
/
database_upgrade.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package ldb
import (
"bytes"
"encoding/binary"
"fmt"
"sort"
"github.com/wangxinyu2018/mass-core/database/storage"
"github.com/wangxinyu2018/mass-core/errors"
"github.com/wangxinyu2018/mass-core/logging"
"github.com/wangxinyu2018/mass-core/massutil"
"github.com/wangxinyu2018/mass-core/txscript"
"github.com/wangxinyu2018/mass-core/wire"
)
var (
ErrUpgradeHeight = errors.New("upgrade error: height")
ErrUpgradeBlockHash = errors.New("upgrade error: block hash")
ErrUpgradeFileNumber = errors.New("upgrade error: file number")
)
func (db *ChainDb) Upgrade_1_1_0() error {
// step 1
// move blocks to disk
err := moveBlockToDisk(db, "[1/3]")
if err != nil {
return err
}
// step 2
// remove empty BANHGT
err = removeEmptyBan(db, "[2/3]")
if err != nil {
return err
}
// step 3
// build STL/HTS index
return buildTxIndex(db, "[3/3]")
}
func moveBlockToDisk(db *ChainDb, progStage string) error {
// get progress
fbs, err := db.getAllBlockFileMeta()
if err != nil {
return err
}
var end uint64
files := make(map[uint32]struct{})
for _, fb := range fbs {
fileNo := binary.LittleEndian.Uint32(fb[0:4])
files[fileNo] = struct{}{}
if int(fileNo) == len(fbs)-1 {
end = binary.LittleEndian.Uint64(fb[24:32]) + 1 // highest block + 1
continue
}
if int(fileNo) > len(fbs)-1 {
logging.CPrint(logging.ERROR, "unexpected error", logging.LogFormat{
"fileNo": fileNo,
"total": len(fbs),
})
return ErrUpgradeFileNumber
}
}
if len(files) != len(fbs) || len(fbs) == 0 {
logging.CPrint(logging.ERROR, "unexpected error", logging.LogFormat{
"files": files,
"expect": len(fbs),
})
return ErrUpgradeFileNumber
}
if db.dbStorageMeta.currentHeight == UnknownHeight {
return ErrUpgradeHeight
}
// find the start height
start := uint64(0)
if end > 100 {
start = end - 100
}
for ; start < end; start++ {
key := makeBlockHeightKey(start)
value, err := db.stor.Get(key)
if err != nil {
logging.CPrint(logging.ERROR, "locate error", logging.LogFormat{
"height": start,
"err": err,
})
return err
}
if len(value) != 52 {
break
}
}
logging.CPrint(logging.INFO, fmt.Sprintf("%s mv blocks to disk", progStage), logging.LogFormat{
"from_height": start,
"to_height": db.dbStorageMeta.currentHeight,
"latest_file": len(fbs) - 1,
})
prog := 0
for cur := start; cur <= db.dbStorageMeta.currentHeight; cur++ {
batch := db.stor.NewBatch()
key := makeBlockHeightKey(cur)
value, err := db.stor.Get(key)
if err != nil {
logging.CPrint(logging.ERROR, "get BLKHGT value error", logging.LogFormat{
"height": cur,
"err": err,
})
return err
}
if len(value) == 52 {
continue
}
// block sha
var blkSha wire.Hash
copy(blkSha[:], value[:32])
rawBlk := value[32:]
blk, err := massutil.NewBlockFromBytes(rawBlk, wire.DB)
if err != nil {
return err
}
blkFile, offset, err := db.blkFileKeeper.SaveRawBlockToDisk(rawBlk, cur, blk.MsgBlock().Header.Timestamp.Unix())
if err != nil {
logging.CPrint(logging.ERROR, "SaveRawBlockToDisk error", logging.LogFormat{
"block": blkSha,
"height": cur,
"err": err,
})
return err
}
// update block index
blkHgtValue := make([]byte, 52)
copy(blkHgtValue[0:], blkSha[:])
binary.LittleEndian.PutUint32(blkHgtValue[32:], blkFile.Number())
binary.LittleEndian.PutUint64(blkHgtValue[32+4:], uint64(offset))
binary.LittleEndian.PutUint64(blkHgtValue[32+12:], uint64(len(rawBlk)))
err = batch.Put(key, blkHgtValue)
if err != nil {
logging.CPrint(logging.ERROR, "update BLKHGT error", logging.LogFormat{
"block": blkSha,
"height": cur,
"err": err,
})
return err
}
err = putLatestBlockFileMeta(batch, blkFile.Bytes())
if err != nil {
logging.CPrint(logging.ERROR, "putLatestBlockFileMeta error", logging.LogFormat{
"block": blkSha,
"height": cur,
"err": err,
})
return err
}
// commit db
err = db.stor.Write(batch)
if err != nil {
logging.CPrint(logging.ERROR, "write db error", logging.LogFormat{
"block": blkSha,
"height": cur,
"err": err,
})
return err
}
db.blkFileKeeper.CommitRecentChange()
// print progress
newProg := (cur - start) * 100 / (db.dbStorageMeta.currentHeight - start)
if int(newProg) >= prog+5 {
prog = int(newProg)
logging.CPrint(logging.INFO, fmt.Sprintf("%s %d%%", progStage, prog), logging.LogFormat{})
}
}
logging.CPrint(logging.INFO, fmt.Sprintf("%s done", progStage), logging.LogFormat{})
return nil
}
func removeEmptyBan(db *ChainDb, progStage string) error {
logging.CPrint(logging.INFO, fmt.Sprintf("%s rm empty BANHGT", progStage), logging.LogFormat{})
removed := 0
iter := db.stor.NewIterator(storage.BytesPrefix(faultPkHeightShaPrefix))
defer iter.Release()
for iter.Next() {
value := iter.Value()
count := binary.LittleEndian.Uint16(value[:2])
if count > 0 {
continue
}
err := db.stor.Delete(iter.Key())
if err != nil {
logging.CPrint(logging.ERROR, "remove ban error", logging.LogFormat{"err": err})
return err
}
removed++
}
logging.CPrint(logging.INFO, fmt.Sprintf("%s done", progStage), logging.LogFormat{"removed": removed})
return nil
}
func removeTxIndex(db *ChainDb, progStage string) error {
batch := db.stor.NewBatch()
defer batch.Release()
// remove HTS
logging.CPrint(logging.INFO, fmt.Sprintf("%s remove HTS start", progStage), logging.LogFormat{})
countHts := 0
iterHts := db.stor.NewIterator(storage.BytesPrefix(shIndexPrefix))
defer iterHts.Release()
for iterHts.Next() {
err := batch.Delete(iterHts.Key())
if err != nil {
return err
}
countHts++
if countHts > 0 && countHts%5000 == 0 {
if err := db.stor.Write(batch); err != nil {
logging.CPrint(logging.ERROR, fmt.Sprintf("%s remove HTS error", progStage), logging.LogFormat{
"err": err,
"batch": countHts / 5000,
})
return err
}
batch.Reset()
}
}
if err := db.stor.Write(batch); err != nil {
logging.CPrint(logging.ERROR, fmt.Sprintf("%s remove HTS error", progStage), logging.LogFormat{
"err": err,
})
return err
}
batch.Reset()
logging.CPrint(logging.INFO, fmt.Sprintf("%s remove HTS done", progStage), logging.LogFormat{"removed": countHts})
// remove STL
logging.CPrint(logging.INFO, fmt.Sprintf("%s remove STL start", progStage), logging.LogFormat{})
countStl := 0
iterStl := db.stor.NewIterator(storage.BytesPrefix(txIndexPrefix))
defer iterStl.Release()
for iterStl.Next() {
err := batch.Delete(iterStl.Key())
if err != nil {
return err
}
countStl++
if countStl > 0 && countStl%5000 == 0 {
if err := db.stor.Write(batch); err != nil {
logging.CPrint(logging.ERROR, fmt.Sprintf("%s remove STL error", progStage), logging.LogFormat{
"err": err,
"batch": countStl / 5000,
})
return err
}
batch.Reset()
}
}
if err := db.stor.Write(batch); err != nil {
logging.CPrint(logging.ERROR, fmt.Sprintf("%s remove STL error", progStage), logging.LogFormat{
"err": err,
})
return err
}
logging.CPrint(logging.INFO, fmt.Sprintf("%s remove STL done", progStage), logging.LogFormat{"removed": countStl})
return nil
}
func writeTxIndex(db *ChainDb, m map[[43]byte][]byte) error {
for k, v := range m {
err := db.stor.Put(k[:], v)
if err != nil {
return err
}
}
return nil
}
func buildTxIndex(db *ChainDb, progStage string) error {
err := removeTxIndex(db, progStage)
if err != nil {
logging.CPrint(logging.ERROR, "remove tx index error", logging.LogFormat{"err": err})
return err
}
logging.CPrint(logging.INFO, fmt.Sprintf("%s build HTS/STL start", progStage), logging.LogFormat{})
type TxInfo struct {
txhash wire.Hash
height uint64
loc wire.TxLoc
spentBuf []byte
isFullySpent bool
}
_, bestHeight, _ := db.NewestSha()
if bestHeight == UnknownHeight {
return ErrUpgradeHeight
}
spentOutpoints := make(map[wire.OutPoint]wire.Hash)
currentHtsMap := make(map[[43]byte][]byte)
currentStlMap := make(map[[43]byte][]byte)
prog := 0
for height := uint64(0); height <= bestHeight; height++ {
if height > 0 {
if height%htsBoundaryDistance == 0 {
if err := writeTxIndex(db, currentHtsMap); err != nil {
return err
}
currentHtsMap = make(map[[43]byte][]byte)
}
if height%stlBoundaryDistance == 0 {
if err := writeTxIndex(db, currentStlMap); err != nil {
return err
}
currentStlMap = make(map[[43]byte][]byte)
}
}
sha, buf, err := db.getBlkByHeight(height)
if err != nil {
return err
}
block, err := massutil.NewBlockFromBytes(buf, wire.DB)
if err != nil {
return err
}
if !bytes.Equal(sha[:], block.Hash()[:]) {
return ErrUpgradeBlockHash
}
// parse block transactions
blkRelatedScriptHash := make(map[wire.Hash]map[wire.TxLoc]bool)
for txIdx, tx := range block.MsgBlock().Transactions {
var txInfo *TxInfo
// fully spent
list, err := db.getTxFullySpent(tx.TxHash().Ptr())
if err != nil && err != storage.ErrNotFound {
logging.CPrint(logging.ERROR, "getTxFullySpent error", logging.LogFormat{
"err": err,
"height": height,
"tx": tx.TxHash(),
})
return err
}
for _, sptx := range list {
if sptx.blkHeight == height {
if sptx.numTxO%8 != 0 || sptx.numTxO < len(tx.TxOut) {
return errors.New("incorrect TxOut number")
}
txInfo = &TxInfo{
height: height,
loc: wire.TxLoc{
TxStart: sptx.txoff,
TxLen: sptx.txlen,
},
isFullySpent: true,
}
break
}
}
if txInfo == nil {
// non fully spent
txInfo = &TxInfo{}
txInfo.height, txInfo.loc.TxStart, txInfo.loc.TxLen, txInfo.spentBuf, err = db.getTxData(tx.TxHash().Ptr())
if err != nil ||
txInfo.height != height ||
len(txInfo.spentBuf)*8 < len(tx.TxOut) {
logging.CPrint(logging.ERROR, "getTxData error",
logging.LogFormat{
"err": err,
"height": height,
"tx": tx.TxHash(),
"txHeight": txInfo.height,
})
return errors.New("getTxData error")
}
}
txInfo.txhash = tx.TxHash()
if txIdx != 0 { // skip coinbase
for vin, txIn := range tx.TxIn {
if scriptHash, ok := spentOutpoints[txIn.PreviousOutPoint]; ok {
delete(spentOutpoints, txIn.PreviousOutPoint)
if _, ok := blkRelatedScriptHash[scriptHash]; !ok {
blkRelatedScriptHash[scriptHash] = make(map[wire.TxLoc]bool)
}
blkRelatedScriptHash[scriptHash][txInfo.loc] = true
} else {
logging.CPrint(logging.FATAL, "unexpected prev outpoint",
logging.LogFormat{
"height": height,
"tx": txInfo.txhash,
"txidx": txIdx,
"vin": vin,
})
}
}
}
for vout, txOut := range tx.TxOut {
class, pops := txscript.GetScriptInfo(txOut.PkScript)
_, scriptHash, err := txscript.GetParsedOpcode(pops, class)
if err != nil {
return err
}
if _, ok := blkRelatedScriptHash[scriptHash]; !ok {
blkRelatedScriptHash[scriptHash] = make(map[wire.TxLoc]bool)
}
blkRelatedScriptHash[scriptHash][txInfo.loc] = true
spent := false
if txInfo.isFullySpent {
spent = true
} else {
byteidx := vout / 8
byteoff := uint(vout % 8)
spent = txInfo.spentBuf[byteidx]&(byte(1)<<byteoff) != 0
}
if spent {
op := wire.OutPoint{Hash: txInfo.txhash, Index: uint32(vout)}
spentOutpoints[op] = scriptHash
}
}
} // range block transaction
// construct HTS/STL record
for scripthash, m := range blkRelatedScriptHash {
slice := make([]wire.TxLoc, 0, len(m))
for txloc := range m {
slice = append(slice, txloc)
}
sort.Slice(slice, func(i, j int) bool {
return slice[i].TxStart < slice[j].TxStart
})
// hts
var htsKey [43]byte
htsKeySlice, htsLowBound := encodeHTSKey(height, scripthash)
copy(htsKey[:], htsKeySlice)
htsBitmap := uint32(0)
htsValue, ok := currentHtsMap[htsKey]
if ok {
htsBitmap = binary.LittleEndian.Uint32(htsValue)
} else {
htsValue = make([]byte, 4)
}
htsBitmap |= 0x01 << (height - htsLowBound)
binary.LittleEndian.PutUint32(htsValue, htsBitmap)
currentHtsMap[htsKey] = htsValue
// stl
var stlKey [43]byte
stlKeySlice, stlLowBound := encodeSTLKey(height, scripthash)
copy(stlKey[:], stlKeySlice)
stlBitmap := uint32(0)
stlValue, ok := currentStlMap[stlKey]
if ok {
stlBitmap = binary.LittleEndian.Uint32(stlValue[0:4])
} else {
stlValue = make([]byte, 4)
}
stlBitmap |= 0x01 << (height - stlLowBound)
binary.LittleEndian.PutUint32(stlValue[0:4], stlBitmap) // set bitmap
suffix := make([]byte, 3+8*len(slice))
suffix[0] = byte(height - stlLowBound) // set index
binary.LittleEndian.PutUint16(suffix[1:3], uint16(len(slice))) // set count
start := 3
for _, txloc := range slice { // set txloc
binary.LittleEndian.PutUint32(suffix[start:start+4], uint32(txloc.TxStart))
binary.LittleEndian.PutUint32(suffix[start+4:start+8], uint32(txloc.TxLen))
start += 8
}
currentStlMap[stlKey] = append(stlValue, suffix...)
}
if int(height*100/bestHeight) >= prog+5 {
prog = int(height * 100 / bestHeight)
logging.CPrint(logging.INFO, fmt.Sprintf("%s %d%%", progStage, prog), logging.LogFormat{})
}
}
err = writeTxIndex(db, currentHtsMap)
if err != nil {
return err
}
return writeTxIndex(db, currentStlMap)
}