-
Notifications
You must be signed in to change notification settings - Fork 151
/
database_hash.go
279 lines (233 loc) · 8.55 KB
/
database_hash.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
package toolset
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"github.com/pkg/errors"
flag "github.com/spf13/pflag"
coreDatabase "github.com/iotaledger/hornet/core/database"
"github.com/iotaledger/hornet/pkg/database"
"github.com/iotaledger/hornet/pkg/model/hornet"
"github.com/iotaledger/hornet/pkg/model/milestone"
"github.com/iotaledger/hornet/pkg/model/storage"
"github.com/iotaledger/hornet/pkg/model/utxo"
"github.com/iotaledger/hornet/pkg/snapshot"
iotago "github.com/iotaledger/iota.go/v2"
)
func calculateDatabaseLedgerHash(dbStorage *storage.Storage, outputJSON bool) error {
correctVersion, err := dbStorage.CheckCorrectDatabasesVersion()
if err != nil {
return err
}
if !correctVersion {
return fmt.Errorf("database version outdated")
}
corrupted, err := dbStorage.AreDatabasesCorrupted()
if err != nil {
return err
}
tainted, err := dbStorage.AreDatabasesTainted()
if err != nil {
return err
}
ts := time.Now()
if !outputJSON {
fmt.Println("calculating ledger state hash...")
}
ledgerIndex, err := dbStorage.UTXOManager().ReadLedgerIndex()
if err != nil {
return err
}
snapshotInfo := dbStorage.SnapshotInfo()
if snapshotInfo == nil {
return errors.New("no snapshot info found")
}
// read out treasury tx
treasuryOutput, err := dbStorage.UTXOManager().UnspentTreasuryOutputWithoutLocking()
if err != nil {
return err
}
var outputs snapshot.LexicalOrderedOutputs
if err := dbStorage.UTXOManager().ForEachUnspentOutput(func(output *utxo.Output) bool {
outputs = append(outputs, &snapshot.Output{MessageID: output.MessageID().ToArray(), OutputID: *output.OutputID(), OutputType: output.OutputType(), Address: output.Address(), Amount: output.Amount()})
return true
}); err != nil {
return err
}
// sort the outputs lexicographically by their OutputID
sort.Sort(outputs)
var solidEntryPoints hornet.LexicalOrderedMessageIDs
dbStorage.ForEachSolidEntryPointWithoutLocking(func(sep *storage.SolidEntryPoint) bool {
solidEntryPoints = append(solidEntryPoints, sep.MessageID)
return true
})
// sort the solid entry points lexicographically by their MessageID
sort.Sort(solidEntryPoints)
// compute the sha256 of the ledger state
lsHash := sha256.New()
// write current ledger index
if err := binary.Write(lsHash, binary.LittleEndian, ledgerIndex); err != nil {
return fmt.Errorf("unable to serialize ledger index: %w", err)
}
var ledgerTokenSupply uint64
if treasuryOutput != nil {
// write current treasury output
if _, err := lsHash.Write(treasuryOutput.MilestoneID[:]); err != nil {
return fmt.Errorf("unable to serialize treasury output milestone hash: %w", err)
}
if err := binary.Write(lsHash, binary.LittleEndian, treasuryOutput.Amount); err != nil {
return fmt.Errorf("unable to serialize treasury output amount: %w", err)
}
ledgerTokenSupply += treasuryOutput.Amount
}
// write all unspent outputs in lexicographical order
for _, output := range outputs {
ledgerTokenSupply += output.Amount
outputBytes, err := output.MarshalBinary()
if err != nil {
return fmt.Errorf("unable to serialize output %s: %w", hex.EncodeToString(output.OutputID[:]), err)
}
if err = binary.Write(lsHash, binary.LittleEndian, outputBytes); err != nil {
return fmt.Errorf("unable to calculate snapshot hash: %w", err)
}
}
if ledgerTokenSupply != iotago.TokenSupply {
return errors.Wrapf(ErrCritical, "ledger token supply does not match the total supply: %d vs %d", ledgerTokenSupply, iotago.TokenSupply)
}
// calculate sha256 hash of the current ledger state
snapshotHashSumWithoutSEPs := lsHash.Sum(nil)
// write all solid entry points in lexicographical order
for _, solidEntryPoint := range solidEntryPoints {
sepBytes, err := solidEntryPoint.MarshalBinary()
if err != nil {
return fmt.Errorf("unable to serialize solid entry point %s: %w", solidEntryPoint.ToHex(), err)
}
if err := binary.Write(lsHash, binary.LittleEndian, sepBytes); err != nil {
return fmt.Errorf("unable to calculate snapshot hash: %w", err)
}
}
snapshotHashSumWithSEPs := lsHash.Sum(nil)
if outputJSON {
type treasuryStruct struct {
MilestoneID string `json:"milestoneID"`
Tokens uint64 `json:"tokens"`
}
var treasury *treasuryStruct
if treasuryOutput != nil {
treasury = &treasuryStruct{
MilestoneID: hex.EncodeToString(treasuryOutput.MilestoneID[:]),
Tokens: treasuryOutput.Amount,
}
}
result := struct {
Healthy bool `json:"healthy"`
Tainted bool `json:"tainted"`
SnapshotTime time.Time `json:"snapshotTime"`
NetworkID uint64 `json:"networkID"`
Treasury *treasuryStruct `json:"treasury"`
LedgerIndex milestone.Index `json:"ledgerIndex"`
SnapshotIndex milestone.Index `json:"snapshotIndex"`
UTXOsCount int `json:"UTXOsCount"`
SEPsCount int `json:"SEPsCount"`
LedgerTokenSupply uint64 `json:"ledgerTokenSupply"`
LedgerStateHash string `json:"ledgerStateHash"`
LedgerStateHashWithSEP string `json:"ledgerStateHashWithSEP"`
}{
Healthy: !corrupted,
Tainted: tainted,
SnapshotTime: snapshotInfo.Timestamp,
NetworkID: snapshotInfo.NetworkID,
Treasury: treasury,
LedgerIndex: ledgerIndex,
SnapshotIndex: snapshotInfo.SnapshotIndex,
UTXOsCount: len(outputs),
SEPsCount: len(solidEntryPoints),
LedgerTokenSupply: ledgerTokenSupply,
LedgerStateHash: hex.EncodeToString(snapshotHashSumWithoutSEPs),
LedgerStateHashWithSEP: hex.EncodeToString(snapshotHashSumWithSEPs),
}
return printJSON(result)
}
fmt.Printf(` >
- Healthy: %s
- Tainted: %s
- Snapshot time: %v
- Network ID: %d
- Treasury: %s
- Ledger index: %d
- Snapshot index: %d
- UTXOs count: %d
- SEPs count: %d
- Ledger token supply: %d
- Ledger state hash (w/o solid entry points): %s
- Ledger state hash (with solid entry points): %s`+"\n\n",
yesOrNo(!corrupted),
yesOrNo(tainted),
snapshotInfo.Timestamp,
snapshotInfo.NetworkID,
func() string {
if treasuryOutput == nil {
return "no treasury output found"
}
return fmt.Sprintf("milestone ID %s, tokens %d", hex.EncodeToString(treasuryOutput.MilestoneID[:]), treasuryOutput.Amount)
}(),
ledgerIndex,
snapshotInfo.SnapshotIndex,
len(outputs),
len(solidEntryPoints),
ledgerTokenSupply,
hex.EncodeToString(snapshotHashSumWithoutSEPs),
hex.EncodeToString(snapshotHashSumWithSEPs),
)
fmt.Printf("successfully calculated ledger state hash, took %v\n", time.Since(ts).Truncate(time.Millisecond))
return nil
}
func databaseLedgerHash(args []string) error {
fs := flag.NewFlagSet("", flag.ContinueOnError)
databasePathFlag := fs.String(FlagToolDatabasePath, DefaultValueMainnetDatabasePath, "the path to the database")
outputJSONFlag := fs.Bool(FlagToolOutputJSON, false, FlagToolDescriptionOutputJSON)
fs.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", ToolDatabaseLedgerHash)
fs.PrintDefaults()
println(fmt.Sprintf("\nexample: %s --%s %s",
ToolDatabaseLedgerHash,
FlagToolDatabasePath,
DefaultValueMainnetDatabasePath))
}
if err := parseFlagSet(fs, args); err != nil {
return err
}
if len(*databasePathFlag) == 0 {
return fmt.Errorf("'%s' not specified", FlagToolDatabasePath)
}
databasePath := *databasePathFlag
if _, err := os.Stat(databasePath); err != nil || os.IsNotExist(err) {
return fmt.Errorf("'%s' (%s) does not exist", FlagToolDatabasePath, databasePath)
}
tangleStore, err := database.StoreWithDefaultSettings(filepath.Join(databasePath, coreDatabase.TangleDatabaseDirectoryName), false)
if err != nil {
return fmt.Errorf("%s database initialization failed: %w", coreDatabase.TangleDatabaseDirectoryName, err)
}
// clean up store
defer func() {
_ = tangleStore.Close()
}()
utxoStore, err := database.StoreWithDefaultSettings(filepath.Join(databasePath, coreDatabase.UTXODatabaseDirectoryName), false)
if err != nil {
return fmt.Errorf("%s database initialization failed: %w", coreDatabase.UTXODatabaseDirectoryName, err)
}
// clean up store
defer func() {
_ = utxoStore.Close()
}()
dbStorage, err := storage.New(tangleStore, utxoStore)
if err != nil {
return err
}
return calculateDatabaseLedgerHash(dbStorage, *outputJSONFlag)
}