-
Notifications
You must be signed in to change notification settings - Fork 11
/
storagehost.go
471 lines (400 loc) · 13.3 KB
/
storagehost.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
// Copyright 2019 DxChain, All rights reserved.
// Use of this source code is governed by an Apache
// License 2.0 that can be found in the LICENSE file.
package storagehost
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"github.com/DxChainNetwork/godx/accounts"
"github.com/DxChainNetwork/godx/common"
tm "github.com/DxChainNetwork/godx/common/threadmanager"
"github.com/DxChainNetwork/godx/ethdb"
"github.com/DxChainNetwork/godx/log"
"github.com/DxChainNetwork/godx/p2p/enode"
"github.com/DxChainNetwork/godx/storage"
sm "github.com/DxChainNetwork/godx/storage/storagehost/storagemanager"
)
// StorageHost provide functions for storageHost management
// It loads or use default config when it have been initialized
// It aims at communicate by protocol with client and lent its own storage to the client
type StorageHost struct {
// backend support
ethBackend storage.HostBackend
parseAPI storage.ParsedAPI
am storage.AccountManager
// storageHost basic config
blockHeight uint64
config storage.HostIntConfig
financialMetrics HostFinancialMetrics
// storage host manager for manipulating the file storage system
sm.StorageManager
lockedStorageResponsibility map[common.Hash]*TryMutex
clientToContract map[string]common.Hash
// things for log and persistence
db *ethdb.LDBDatabase
persistDir string
log log.Logger
// things for thread safety
lock sync.RWMutex
tm tm.ThreadManager
}
// IsContractSignedWithClient check whether this host signed a contract with the given client
func (h *StorageHost) IsContractSignedWithClient(clientNode *enode.Node) bool {
h.lock.RLock()
defer h.lock.RUnlock()
if _, exists := h.clientToContract[clientNode.String()]; exists {
return true
}
return false
}
// UpdateContractToClientNodeMappingAndConnection will update the contract that host signed
// with the storage client. For any contract that are not contained in the storage
// responsibility, it means host had not signed the contract with the client. The
// connection will be removed from the static and the contract information will be
// deleted from the record
func (h *StorageHost) UpdateContractToClientNodeMappingAndConnection() {
h.lock.Lock()
defer h.lock.Unlock()
// loop through the clientToContract mapping, found those
// are not included in the storage responsibility, and delete
// them from the clientToContract mapping
for clientURL, contractID := range h.clientToContract {
if _, exists := h.lockedStorageResponsibility[contractID]; !exists {
delete(h.clientToContract, clientURL)
// parse the client URL to node
clientNode, err := enode.ParseV4(clientURL)
if err != nil {
continue
}
h.ethBackend.CheckAndUpdateConnection(clientNode)
}
}
}
// RetrieveExternalConfig is used to get the storage host's external
// configuration
func (h *StorageHost) RetrieveExternalConfig() storage.HostExtConfig {
return h.externalConfig()
}
// GetCurrentBlockHeight is used to retrieve the current
// block height saved in the storage host
func (h *StorageHost) GetCurrentBlockHeight() uint64 {
h.lock.RLock()
defer h.lock.RUnlock()
return h.blockHeight
}
// New Initialize the Host, including init the structure
// load or use the default config, init db and ext.
func New(persistDir string) (*StorageHost, error) {
// do a host creation, but incomplete config
h := StorageHost{
log: log.New(),
persistDir: persistDir,
lockedStorageResponsibility: make(map[common.Hash]*TryMutex),
clientToContract: make(map[string]common.Hash),
}
var err error
// Create the data path
if err = os.MkdirAll(h.persistDir, 0700); err != nil {
return nil, err
}
// initialize the storage manager
if h.StorageManager, err = sm.New(persistDir); err != nil {
return nil, err
}
// open the database
if h.db, err = openDB(filepath.Join(persistDir, databaseFile)); err != nil {
return nil, err
}
return &h, nil
}
// Start loads all APIs and make them mapping, also introduce the account
// manager as a member variable in side the StorageHost
func (h *StorageHost) Start(eth storage.HostBackend) (err error) {
// init the account manager
h.am = eth.AccountManager()
h.ethBackend = eth
// load the data from file or from default config
if err = h.load(); err != nil {
return err
}
// start the storage manager
if err = h.StorageManager.Start(); err != nil {
return err
}
// parse storage contract tx API
err = storage.FilterAPIs(h.ethBackend.APIs(), &h.parseAPI)
if err != nil {
h.log.Error("responsibilityFailed to parse storage contract tx API for host", "error", err)
return
}
//Delete residual storage responsibility
if err = h.pruneStaleStorageResponsibilities(); err != nil {
return err
}
// subscribe block chain change event
go h.subscribeChainChangEvent()
return nil
}
// Close the storage host and persist the data
func (h *StorageHost) Close() error {
err := h.tm.Stop()
newErr := h.StorageManager.Close()
err = common.ErrCompose(err, newErr)
h.db.Close()
newErr = h.syncConfig()
err = common.ErrCompose(err, newErr)
return err
}
// load do the following things:
// 1. load the config from file
// 2. if the config file not found, create the config file, and use the default config
// 3. synchronize the data to config file
func (h *StorageHost) load() error {
h.lock.Lock()
defer h.lock.Unlock()
// try to load from the config files,
if err := h.loadConfig(); err == nil {
return err
} else if !os.IsNotExist(err) {
// if the error is NOT caused by FILE NOT FOUND Exception
return err
}
// At this step, the error is caused by FILE NOT FOUND Exception
// Create the config file
h.log.Info("Creat a new HostSetting file")
// currently the error is caused by file not found exception
// create the file
file, err := os.Create(filepath.Join(h.persistDir, HostSettingFile))
if err != nil {
// if the error is throw when create the file
// close the file and directly return the error
_ = file.Close()
return err
}
// assert the error is nil, close the file
if err := file.Close(); err != nil {
return err
}
// load the default config
h.config = defaultConfig()
// and get synchronization
if syncErr := h.syncConfig(); syncErr != nil {
h.log.Warn("Tempt to synchronize config to file responsibilityFailed: " + syncErr.Error())
}
return nil
}
// getPaymentAddress get the current payment address. If no address is set, assign the first
// account address as the payment address
func (h *StorageHost) getPaymentAddress() (common.Address, error) {
h.lock.RLock()
paymentAddress := h.config.PaymentAddress
h.lock.RUnlock()
if paymentAddress != (common.Address{}) {
return paymentAddress, nil
}
//Local node does not contain wallet
if wallets := h.am.Wallets(); len(wallets) > 0 {
//The local node does not have any wallet address yet
if accs := wallets[0].Accounts(); len(accs) > 0 {
paymentAddress := accs[0].Address
//the first address in the local wallet will be used as the paymentAddress by default.
h.lock.Lock()
defer h.lock.Unlock()
// Check again
if h.config.PaymentAddress == (common.Address{}) {
h.config.PaymentAddress = paymentAddress
if err := h.syncConfig(); err != nil {
return common.Address{}, fmt.Errorf("cannot save host config: %v", err)
}
return paymentAddress, nil
}
return h.config.PaymentAddress, nil
}
}
return common.Address{}, errors.New("no wallet accounts available")
}
// getInternalConfig Return the internal config of host
func (h *StorageHost) getInternalConfig() storage.HostIntConfig {
h.lock.RLock()
defer h.lock.RUnlock()
return h.config
}
// getFinancialMetrics contains the information about the activities,
// commitments, rewards of host
func (h *StorageHost) getFinancialMetrics() HostFinancialMetrics {
h.lock.RLock()
defer h.lock.RUnlock()
return h.financialMetrics
}
// getPersistDir return the persist directory of the host
func (h *StorageHost) getPersistDir() string {
h.lock.RLock()
defer h.lock.RUnlock()
return h.persistDir
}
// setAcceptContracts set the HostIntConfig.AcceptingContracts to value
func (h *StorageHost) setAcceptContracts(val bool) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.AcceptingContracts = val
return h.syncConfig()
}
// setMaxDownloadBatch set the MaxDownloadBatchSize
func (h *StorageHost) setMaxDownloadBatchSize(val uint64) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.MaxDownloadBatchSize = val
return h.syncConfig()
}
// setMaxDuration set the MaxDuration
func (h *StorageHost) setMaxDuration(val uint64) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.MaxDuration = val
return h.syncConfig()
}
// setMaxReviseBatchSize set the MaxReviseBatchSize
func (h *StorageHost) setMaxReviseBatchSize(val uint64) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.MaxReviseBatchSize = val
return h.syncConfig()
}
// setPaymentAddress set the account to the address
func (h *StorageHost) setPaymentAddress(addr common.Address) error {
account := accounts.Account{Address: addr}
_, err := h.am.Find(account)
if err != nil {
return errors.New("unknown account")
}
h.lock.Lock()
defer h.lock.Unlock()
h.config.PaymentAddress = addr
return h.syncConfig()
}
// setDeposit set the deposit to val
func (h *StorageHost) setDeposit(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.Deposit = val
return h.syncConfig()
}
// setDepositBudget set the DepositBudget to val
func (h *StorageHost) setDepositBudget(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.DepositBudget = val
return h.syncConfig()
}
// setMaxDeposit set the MaxDeposit to val
func (h *StorageHost) setMaxDeposit(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.MaxDeposit = val
return h.syncConfig()
}
// setBaseRPCPrice set the BaseRPCPrice to val
func (h *StorageHost) setBaseRPCPrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.BaseRPCPrice = val
return h.syncConfig()
}
// setContractPrice set the ContractPrice to val
func (h *StorageHost) setContractPrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.ContractPrice = val
return h.syncConfig()
}
// setDownloadBandwidthPrice set the DownloadBandwidthPrice to val
func (h *StorageHost) setDownloadBandwidthPrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.DownloadBandwidthPrice = val
return h.syncConfig()
}
// setSectorAccessPrice set the SectorAccessPrice to val
func (h *StorageHost) setSectorAccessPrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.SectorAccessPrice = val
return h.syncConfig()
}
// setStoragePrice set the StoragePrice to val
func (h *StorageHost) setStoragePrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.StoragePrice = val
return h.syncConfig()
}
// setUploadBandwidthPrice set the UploadBandwidthPrice to val
func (h *StorageHost) setUploadBandwidthPrice(val common.BigInt) error {
h.lock.Lock()
defer h.lock.Unlock()
h.config.UploadBandwidthPrice = val
return h.syncConfig()
}
//return the externalConfig for host
func (h *StorageHost) externalConfig() storage.HostExtConfig {
h.lock.Lock()
defer h.lock.Unlock()
// Get the total and remaining disk space
var totalStorageSpace uint64
var remainingStorageSpace uint64
hs := h.StorageManager.AvailableSpace()
totalStorageSpace = storage.SectorSize * hs.TotalSectors
remainingStorageSpace = storage.SectorSize * hs.FreeSectors
acceptingContracts := h.config.AcceptingContracts
MaxDeposit := h.config.MaxDeposit
paymentAddress := h.config.PaymentAddress
if paymentAddress == (common.Address{}) {
acceptingContracts = false
return storage.HostExtConfig{AcceptingContracts: false}
}
account := accounts.Account{Address: paymentAddress}
wallet, err := h.am.Find(account)
if err != nil {
h.log.Warn("Failed to find the wallet", "err", err)
acceptingContracts = false
}
//If the wallet is locked, you will not be able to enter the signing phase.
status, err := wallet.Status()
if status == "Locked" || err != nil {
h.log.Warn("Wallet is not unlocked", "err", err)
acceptingContracts = false
}
stateDB, err := h.ethBackend.GetBlockChain().State()
if err != nil {
h.log.Warn("Failed to find the stateDB", "err", err)
} else {
balance := stateDB.GetBalance(paymentAddress)
//If the maximum deposit amount exceeds the account balance, set it as the account balance
if balance.Cmp(MaxDeposit.BigIntPtr()) < 0 {
MaxDeposit = common.PtrBigInt(balance)
}
}
return storage.HostExtConfig{
AcceptingContracts: acceptingContracts,
MaxDownloadBatchSize: h.config.MaxDownloadBatchSize,
MaxDuration: h.config.MaxDuration,
MaxReviseBatchSize: h.config.MaxReviseBatchSize,
SectorSize: storage.SectorSize,
WindowSize: h.config.WindowSize,
PaymentAddress: paymentAddress,
TotalStorage: totalStorageSpace,
RemainingStorage: remainingStorageSpace,
Deposit: h.config.Deposit,
MaxDeposit: MaxDeposit,
BaseRPCPrice: h.config.BaseRPCPrice,
ContractPrice: h.config.ContractPrice,
DownloadBandwidthPrice: h.config.DownloadBandwidthPrice,
SectorAccessPrice: h.config.SectorAccessPrice,
StoragePrice: h.config.StoragePrice,
UploadBandwidthPrice: h.config.UploadBandwidthPrice,
Version: storage.ConfigVersion,
}
}