diff --git a/cmd/hostd/consts_default.go b/cmd/hostd/consts_default.go index 6a814b44..71c05850 100644 --- a/cmd/hostd/consts_default.go +++ b/cmd/hostd/consts_default.go @@ -8,9 +8,9 @@ const ( logPathEnvVariable = "HOSTD_LOG_PATH" configPathEnvVariable = "HOSTD_CONFIG_FILE" - defaultAPIAddr = "localhost:9980" - defaultGatewayAddr = ":9981" - defaultRHPv2Addr = ":9982" - defaultRHPv3TCPAddr = ":9983" - defaultRHPv3WSAddr = ":9984" + defaultAPIAddr = "localhost:9980" + defaultGatewayAddr = ":9981" + defaultRHP2Addr = ":9982" + defaultRHP3TCPAddr = ":9983" + defaultRHP3WSAddr = ":9984" ) diff --git a/cmd/hostd/consts_testnet.go b/cmd/hostd/consts_testnet.go index 73caba38..f0a7f06a 100644 --- a/cmd/hostd/consts_testnet.go +++ b/cmd/hostd/consts_testnet.go @@ -8,9 +8,9 @@ const ( logPathEnvVariable = "HOSTD_ZEN_LOG_PATH" configPathEnvVariable = "HOSTD_ZEN_CONFIG_FILE" - defaultAPIAddr = "localhost:9880" - defaultGatewayAddr = ":9881" - defaultRHPv2Addr = ":9882" - defaultRHPv3TCPAddr = ":9883" - defaultRHPv3WSAddr = ":9884" + defaultAPIAddr = "localhost:9880" + defaultGatewayAddr = ":9881" + defaultRHP2Addr = ":9882" + defaultRHP3TCPAddr = ":9883" + defaultRHP3WSAddr = ":9884" ) diff --git a/cmd/hostd/main.go b/cmd/hostd/main.go index a4907665..f1745b36 100644 --- a/cmd/hostd/main.go +++ b/cmd/hostd/main.go @@ -41,11 +41,11 @@ var ( Bootstrap: true, }, RHP2: config.RHP2{ - Address: defaultRHPv2Addr, + Address: defaultRHP2Addr, }, RHP3: config.RHP3{ - TCPAddress: defaultRHPv3TCPAddr, - WebSocketAddress: defaultRHPv3WSAddr, + TCPAddress: defaultRHP3TCPAddr, + WebSocketAddress: defaultRHP3WSAddr, }, Log: config.Log{ Level: "info", @@ -335,18 +335,18 @@ func main() { } defer web.Close() - rhpv3WS := http.Server{ + rhp3WS := http.Server{ Handler: node.rhp3.WebSocketHandler(), ReadTimeout: 30 * time.Second, TLSConfig: node.settings.RHP3TLSConfig(), ErrorLog: stdlog.New(io.Discard, "", 0), } - defer rhpv3WS.Close() + defer rhp3WS.Close() go func() { - err := rhpv3WS.ServeTLS(rhp3WSListener, "", "") + err := rhp3WS.ServeTLS(rhp3WSListener, "", "") if err != nil && !errors.Is(err, http.ErrServerClosed) { - log.Error("failed to serve rhpv3 websocket", zap.Error(err)) + log.Error("failed to serve rhp3 websocket", zap.Error(err)) } }() diff --git a/cmd/hostd/node.go b/cmd/hostd/node.go index 46a60df6..59b275b2 100644 --- a/cmd/hostd/node.go +++ b/cmd/hostd/node.go @@ -18,8 +18,8 @@ import ( "go.sia.tech/hostd/internal/chain" "go.sia.tech/hostd/persist/sqlite" "go.sia.tech/hostd/rhp" - rhpv2 "go.sia.tech/hostd/rhp/v2" - rhpv3 "go.sia.tech/hostd/rhp/v3" + rhp2 "go.sia.tech/hostd/rhp/v2" + rhp3 "go.sia.tech/hostd/rhp/v3" "go.sia.tech/hostd/wallet" "go.sia.tech/siad/modules" "go.sia.tech/siad/modules/consensus" @@ -45,9 +45,9 @@ type node struct { sessions *rhp.SessionReporter rhp2Monitor *rhp.DataRecorder - rhp2 *rhpv2.SessionHandler + rhp2 *rhp2.SessionHandler rhp3Monitor *rhp.DataRecorder - rhp3 *rhpv3.SessionHandler + rhp3 *rhp3.SessionHandler } func (n *node) Close() error { @@ -65,8 +65,8 @@ func (n *node) Close() error { return nil } -func startRHP2(l net.Listener, hostKey types.PrivateKey, rhp3Addr string, cs rhpv2.ChainManager, tp rhpv2.TransactionPool, w rhpv2.Wallet, cm rhpv2.ContractManager, sr rhpv2.SettingsReporter, sm rhpv2.StorageManager, monitor rhp.DataMonitor, sessions *rhp.SessionReporter, log *zap.Logger) (*rhpv2.SessionHandler, error) { - rhp2, err := rhpv2.NewSessionHandler(l, hostKey, rhp3Addr, cs, tp, w, cm, sr, sm, monitor, sessions, log) +func startRHP2(l net.Listener, hostKey types.PrivateKey, rhp3Addr string, cs rhp2.ChainManager, tp rhp2.TransactionPool, w rhp2.Wallet, cm rhp2.ContractManager, sr rhp2.SettingsReporter, sm rhp2.StorageManager, monitor rhp.DataMonitor, sessions *rhp.SessionReporter, log *zap.Logger) (*rhp2.SessionHandler, error) { + rhp2, err := rhp2.NewSessionHandler(l, hostKey, rhp3Addr, cs, tp, w, cm, sr, sm, monitor, sessions, log) if err != nil { return nil, err } @@ -74,8 +74,8 @@ func startRHP2(l net.Listener, hostKey types.PrivateKey, rhp3Addr string, cs rhp return rhp2, nil } -func startRHP3(l net.Listener, hostKey types.PrivateKey, cs rhpv3.ChainManager, tp rhpv3.TransactionPool, w rhpv3.Wallet, am rhpv3.AccountManager, cm rhpv3.ContractManager, rm rhpv3.RegistryManager, sr rhpv3.SettingsReporter, sm rhpv3.StorageManager, monitor rhp.DataMonitor, sessions *rhp.SessionReporter, log *zap.Logger) (*rhpv3.SessionHandler, error) { - rhp3, err := rhpv3.NewSessionHandler(l, hostKey, cs, tp, w, am, cm, rm, sm, sr, monitor, sessions, log) +func startRHP3(l net.Listener, hostKey types.PrivateKey, cs rhp3.ChainManager, tp rhp3.TransactionPool, w rhp3.Wallet, am rhp3.AccountManager, cm rhp3.ContractManager, rm rhp3.RegistryManager, sr rhp3.SettingsReporter, sm rhp3.StorageManager, monitor rhp.DataMonitor, sessions *rhp.SessionReporter, log *zap.Logger) (*rhp3.SessionHandler, error) { + rhp3, err := rhp3.NewSessionHandler(l, hostKey, cs, tp, w, am, cm, rm, sm, sr, monitor, sessions, log) if err != nil { return nil, err } @@ -183,13 +183,13 @@ func newNode(walletKey types.PrivateKey, logger *zap.Logger) (*node, types.Priva sessions := rhp.NewSessionReporter() rhp2Monitor := rhp.NewDataRecorder(&rhp2MonitorStore{db}, logger.Named("rhp2Monitor")) - rhp2, err := startRHP2(rhp2Listener, hostKey, rhp3Listener.Addr().String(), cm, tp, w, contractManager, sr, sm, rhp2Monitor, sessions, logger.Named("rhpv2")) + rhp2, err := startRHP2(rhp2Listener, hostKey, rhp3Listener.Addr().String(), cm, tp, w, contractManager, sr, sm, rhp2Monitor, sessions, logger.Named("rhp2")) if err != nil { return nil, types.PrivateKey{}, fmt.Errorf("failed to start rhp2: %w", err) } rhp3Monitor := rhp.NewDataRecorder(&rhp3MonitorStore{db}, logger.Named("rhp3Monitor")) - rhp3, err := startRHP3(rhp3Listener, hostKey, cm, tp, w, accountManager, contractManager, registryManager, sr, sm, rhp3Monitor, sessions, logger.Named("rhpv3")) + rhp3, err := startRHP3(rhp3Listener, hostKey, cm, tp, w, accountManager, contractManager, registryManager, sr, sm, rhp3Monitor, sessions, logger.Named("rhp3")) if err != nil { return nil, types.PrivateKey{}, fmt.Errorf("failed to start rhp3: %w", err) } diff --git a/host/accounts/accounts.go b/host/accounts/accounts.go index da6af900..1212d1f8 100644 --- a/host/accounts/accounts.go +++ b/host/accounts/accounts.go @@ -6,7 +6,7 @@ import ( "sync" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/contracts" "go.sia.tech/hostd/host/settings" @@ -25,16 +25,16 @@ type ( // An AccountStore stores and updates account balances. AccountStore interface { // AccountFunding returns the remaining funding sources for an account. - AccountFunding(accountID rhpv3.Account) ([]FundingSource, error) + AccountFunding(accountID rhp3.Account) ([]FundingSource, error) // Accounts returns a list of active ephemeral accounts Accounts(limit, offset int) ([]Account, error) // AccountBalance returns the balance of the account with the given ID. - AccountBalance(accountID rhpv3.Account) (types.Currency, error) + AccountBalance(accountID rhp3.Account) (types.Currency, error) // CreditAccountWithContract adds the specified amount to the account with the given ID. CreditAccountWithContract(FundAccountWithContract) (types.Currency, error) // DebitAccount subtracts the specified amount from the account with the given // ID. Returns the remaining balance of the account. - DebitAccount(accountID rhpv3.Account, usage Usage) (types.Currency, error) + DebitAccount(accountID rhp3.Account, usage Usage) (types.Currency, error) } // Settings returns the host's current settings. @@ -50,13 +50,13 @@ type ( // FundingSource tracks a funding source for an account. FundingSource struct { ContractID types.FileContractID `json:"contractID"` - AccountID rhpv3.Account `json:"accountID"` + AccountID rhp3.Account `json:"accountID"` Amount types.Currency `json:"amount"` } // An Account holds the balance and expiration of an ephemeral account. Account struct { - ID rhpv3.Account `json:"ID"` + ID rhp3.Account `json:"ID"` Balance types.Currency `json:"balance"` Expiration time.Time `json:"expiration"` } @@ -64,7 +64,7 @@ type ( // FundAccountWithContract is a helper struct for funding an account with a // contract. FundAccountWithContract struct { - Account rhpv3.Account + Account rhp3.Account Cost types.Currency Amount types.Currency Revision contracts.SignedRevision @@ -81,11 +81,11 @@ type ( // balances is a map of account IDs to their current balance. It // is used for consistency before a budget is synced to the underlying // store. - balances map[rhpv3.Account]accountState + balances map[rhp3.Account]accountState } ) -func (am *AccountManager) getBalance(accountID rhpv3.Account) (types.Currency, error) { +func (am *AccountManager) getBalance(accountID rhp3.Account) (types.Currency, error) { if state, ok := am.balances[accountID]; ok { return state.balance, nil } @@ -93,7 +93,7 @@ func (am *AccountManager) getBalance(accountID rhpv3.Account) (types.Currency, e } // Balance returns the balance of the account with the given ID. -func (am *AccountManager) Balance(accountID rhpv3.Account) (types.Currency, error) { +func (am *AccountManager) Balance(accountID rhp3.Account) (types.Currency, error) { am.mu.Lock() defer am.mu.Unlock() return am.getBalance(accountID) @@ -105,7 +105,7 @@ func (am *AccountManager) Accounts(limit, offset int) (acc []Account, err error) } // AccountFunding returns the remaining funding sources for an account. -func (am *AccountManager) AccountFunding(account rhpv3.Account) (srcs []FundingSource, err error) { +func (am *AccountManager) AccountFunding(account rhp3.Account) (srcs []FundingSource, err error) { return am.store.AccountFunding(account) } @@ -143,7 +143,7 @@ func (am *AccountManager) Credit(req FundAccountWithContract, refund bool) (type // Budget creates a new budget for an account limited by amount. The spent // amount will not be synced to the underlying store until Commit is called. -func (am *AccountManager) Budget(accountID rhpv3.Account, amount types.Currency) (*Budget, error) { +func (am *AccountManager) Budget(accountID rhp3.Account, amount types.Currency) (*Budget, error) { am.mu.Lock() defer am.mu.Unlock() @@ -188,6 +188,6 @@ func NewManager(store AccountStore, settings Settings) *AccountManager { store: store, settings: settings, - balances: make(map[rhpv3.Account]accountState), + balances: make(map[rhp3.Account]accountState), } } diff --git a/host/accounts/budget.go b/host/accounts/budget.go index da158759..b19973a3 100644 --- a/host/accounts/budget.go +++ b/host/accounts/budget.go @@ -3,7 +3,7 @@ package accounts import ( "fmt" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" ) @@ -21,7 +21,7 @@ type ( // A Budget transactionally manages an account's balance. It is not safe for // concurrent use. Budget struct { - accountID rhpv3.Account + accountID rhp3.Account max types.Currency usage Usage committed bool diff --git a/host/contracts/actions.go b/host/contracts/actions.go index 86eb3158..f34726fb 100644 --- a/host/contracts/actions.go +++ b/host/contracts/actions.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.uber.org/zap" @@ -28,8 +28,8 @@ func (cm *ContractManager) buildStorageProof(id types.FileContractID, filesize u }, nil } - sectorIndex := index / rhpv2.LeavesPerSector - segmentIndex := index % rhpv2.LeavesPerSector + sectorIndex := index / rhp2.LeavesPerSector + segmentIndex := index % rhp2.LeavesPerSector roots, err := cm.SectorRoots(id, 0, 0) if err != nil { @@ -40,13 +40,13 @@ func (cm *ContractManager) buildStorageProof(id types.FileContractID, filesize u if err != nil { return types.StorageProof{}, err } - segmentProof := rhpv2.ConvertProofOrdering(rhpv2.BuildProof(sector, segmentIndex, segmentIndex+1, nil), segmentIndex) - sectorProof := rhpv2.ConvertProofOrdering(rhpv2.BuildSectorRangeProof(roots, sectorIndex, sectorIndex+1), sectorIndex) + segmentProof := rhp2.ConvertProofOrdering(rhp2.BuildProof(sector, segmentIndex, segmentIndex+1, nil), segmentIndex) + sectorProof := rhp2.ConvertProofOrdering(rhp2.BuildSectorRangeProof(roots, sectorIndex, sectorIndex+1), sectorIndex) sp := types.StorageProof{ ParentID: id, Proof: append(segmentProof, sectorProof...), } - copy(sp.Leaf[:], sector[segmentIndex*rhpv2.LeafSize:]) + copy(sp.Leaf[:], sector[segmentIndex*rhp2.LeafSize:]) return sp, nil } diff --git a/host/contracts/contracts.go b/host/contracts/contracts.go index 3683e1fd..4b2fb61d 100644 --- a/host/contracts/contracts.go +++ b/host/contracts/contracts.go @@ -8,7 +8,7 @@ import ( "time" lru "github.com/hashicorp/golang-lru/v2" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.uber.org/zap" ) @@ -309,7 +309,7 @@ func (cu *ContractUpdater) SectorRoot(i uint64) (types.Hash256, error) { // MerkleRoot returns the merkle root of the contract's sector roots. func (cu *ContractUpdater) MerkleRoot() types.Hash256 { - return rhpv2.MetaRoot(cu.sectorRoots) + return rhp2.MetaRoot(cu.sectorRoots) } // SectorRoots returns a copy of the current state of the contract's sector roots. diff --git a/host/contracts/integrity.go b/host/contracts/integrity.go index c7bd7719..495486d1 100644 --- a/host/contracts/integrity.go +++ b/host/contracts/integrity.go @@ -8,7 +8,7 @@ import ( "strings" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.uber.org/zap" @@ -71,14 +71,14 @@ func (cm *ContractManager) CheckIntegrity(ctx context.Context, contractID types. } defer cm.Unlock(contractID) - expectedRoots := contract.Revision.Filesize / rhpv2.SectorSize + expectedRoots := contract.Revision.Filesize / rhp2.SectorSize roots, err := cm.getSectorRoots(contractID, 0, 0) if err != nil { return nil, 0, fmt.Errorf("failed to get sector roots: %w", err) } else if uint64(len(roots)) != expectedRoots { return nil, 0, fmt.Errorf("expected %v sector roots, got %v", expectedRoots, len(roots)) - } else if calculated := rhpv2.MetaRoot(roots); contract.Revision.FileMerkleRoot != calculated { + } else if calculated := rhp2.MetaRoot(roots); contract.Revision.FileMerkleRoot != calculated { return nil, 0, fmt.Errorf("expected Merkle root %v, got %v", contract.Revision.FileMerkleRoot, calculated) } @@ -123,7 +123,7 @@ func (cm *ContractManager) CheckIntegrity(ctx context.Context, contractID types. log.Error("missing sector", zap.String("root", root.String()), zap.Error(err)) missing++ results <- IntegrityResult{ExpectedRoot: root, Error: err} - } else if calculated := rhpv2.SectorRoot(sector); root != calculated { // sector data corrupt + } else if calculated := rhp2.SectorRoot(sector); root != calculated { // sector data corrupt log.Error("corrupt sector", zap.String("root", root.String()), zap.String("actual", calculated.String())) corrupt++ results <- IntegrityResult{ExpectedRoot: root, ActualRoot: calculated, Error: errors.New("sector data corrupt")} diff --git a/host/contracts/integrity_test.go b/host/contracts/integrity_test.go index fd68a6c2..3af87d80 100644 --- a/host/contracts/integrity_test.go +++ b/host/contracts/integrity_test.go @@ -10,7 +10,7 @@ import ( "testing" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.sia.tech/hostd/host/contracts" @@ -138,9 +138,9 @@ func TestCheckIntegrity(t *testing.T) { var roots []types.Hash256 var releases []func() error for i := 0; i < 5; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := s.Write(root, §or) if err != nil { t.Fatal(err) @@ -151,8 +151,8 @@ func TestCheckIntegrity(t *testing.T) { } contract.Revision.RevisionNumber++ - contract.Revision.Filesize = uint64(len(roots)) * rhpv2.SectorSize - contract.Revision.FileMerkleRoot = rhpv2.MetaRoot(roots) + contract.Revision.Filesize = uint64(len(roots)) * rhp2.SectorSize + contract.Revision.FileMerkleRoot = rhp2.MetaRoot(roots) if err := updater.Commit(contract.SignedRevision, contracts.Usage{}); err != nil { t.Fatal(err) diff --git a/host/contracts/manager.go b/host/contracts/manager.go index d8b5ecec..5a8ef635 100644 --- a/host/contracts/manager.go +++ b/host/contracts/manager.go @@ -13,7 +13,7 @@ import ( lru "github.com/hashicorp/golang-lru/v2" "gitlab.com/NebulousLabs/encoding" "go.sia.tech/core/consensus" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.sia.tech/hostd/internal/chain" @@ -61,7 +61,7 @@ type ( // A StorageManager stores and retrieves sectors. StorageManager interface { // Read reads a sector from the store - Read(root types.Hash256) (*[rhpv2.SectorSize]byte, error) + Read(root types.Hash256) (*[rhp2.SectorSize]byte, error) } // Alerts registers and dismisses global alerts. diff --git a/host/contracts/revenue_test.go b/host/contracts/revenue_test.go index 2a70d5f6..a74d3aea 100644 --- a/host/contracts/revenue_test.go +++ b/host/contracts/revenue_test.go @@ -68,12 +68,12 @@ func TestRevenueMetrics(t *testing.T) { t.Fatal(err) } - settings, err := host.RHPv2Settings() + settings, err := host.RHP2Settings() if err != nil { t.Fatal(err) } - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) if err != nil { t.Fatal(err) } @@ -90,7 +90,7 @@ func TestRevenueMetrics(t *testing.T) { time.Sleep(100 * time.Millisecond) // sync time // start an RHP3 session - sess, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + sess, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } @@ -225,12 +225,12 @@ func TestRevenueMetrics(t *testing.T) { t.Fatal(err) } - settings, err := host.RHPv2Settings() + settings, err := host.RHP2Settings() if err != nil { t.Fatal(err) } - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) if err != nil { t.Fatal(err) } @@ -247,7 +247,7 @@ func TestRevenueMetrics(t *testing.T) { time.Sleep(100 * time.Millisecond) // sync time // start an RHP3 session - sess, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + sess, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } @@ -369,12 +369,12 @@ func TestRevenueMetrics(t *testing.T) { t.Fatal(err) } - settings, err := host.RHPv2Settings() + settings, err := host.RHP2Settings() if err != nil { t.Fatal(err) } - r1, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) + r1, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) if err != nil { t.Fatal(err) } @@ -391,7 +391,7 @@ func TestRevenueMetrics(t *testing.T) { time.Sleep(100 * time.Millisecond) // sync time // form a second contract - r2, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) + r2, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), host.TipState().Index.Height+200) if err != nil { t.Fatal(err) } @@ -409,7 +409,7 @@ func TestRevenueMetrics(t *testing.T) { } // start an RHP3 session - sess, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + sess, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } diff --git a/host/registry/registry.go b/host/registry/registry.go index 45bd562b..8f2bc009 100644 --- a/host/registry/registry.go +++ b/host/registry/registry.go @@ -5,7 +5,7 @@ import ( "fmt" "sync" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/internal/threadgroup" "go.uber.org/zap" @@ -27,11 +27,11 @@ type ( Store interface { // GetRegistryValue returns the registry value for the given key. If the key is not // found should return ErrEntryNotFound. - GetRegistryValue(key rhpv3.RegistryKey) (entry rhpv3.RegistryValue, _ error) + GetRegistryValue(key rhp3.RegistryKey) (entry rhp3.RegistryValue, _ error) // SetRegistryValue sets the registry value for the given key. If the // value would exceed the maximum number of entries, should return // ErrNotEnoughSpace. - SetRegistryValue(entry rhpv3.RegistryEntry, expiration uint64) error + SetRegistryValue(entry rhp3.RegistryEntry, expiration uint64) error // RegistryEntries returns the current number of entries as well as the // maximum number of entries the registry can hold. RegistryEntries() (count uint64, total uint64, err error) @@ -67,7 +67,7 @@ func (r *Manager) Entries() (count uint64, total uint64, err error) { } // Get returns the registry value for the provided key. -func (r *Manager) Get(key rhpv3.RegistryKey) (value rhpv3.RegistryValue, err error) { +func (r *Manager) Get(key rhp3.RegistryKey) (value rhp3.RegistryValue, err error) { r.mu.Lock() defer r.mu.Unlock() value, err = r.store.GetRegistryValue(key) @@ -79,12 +79,12 @@ func (r *Manager) Get(key rhpv3.RegistryKey) (value rhpv3.RegistryValue, err err // Put creates or updates the registry value for the provided key. If err is nil // the new value is returned, otherwise the previous value is returned. -func (r *Manager) Put(entry rhpv3.RegistryEntry, expirationHeight uint64) (rhpv3.RegistryValue, error) { +func (r *Manager) Put(entry rhp3.RegistryEntry, expirationHeight uint64) (rhp3.RegistryValue, error) { r.mu.Lock() defer r.mu.Unlock() - if err := rhpv3.ValidateRegistryEntry(entry); err != nil { - return rhpv3.RegistryValue{}, fmt.Errorf("invalid registry entry: %w", err) + if err := rhp3.ValidateRegistryEntry(entry); err != nil { + return rhp3.RegistryValue{}, fmt.Errorf("invalid registry entry: %w", err) } // get the current value. @@ -98,12 +98,12 @@ func (r *Manager) Put(entry rhpv3.RegistryEntry, expirationHeight uint64) (rhpv3 } else if err != nil { return old, fmt.Errorf("failed to get registry value: %w", err) } - oldEntry := rhpv3.RegistryEntry{ + oldEntry := rhp3.RegistryEntry{ RegistryKey: entry.RegistryKey, RegistryValue: old, } - if err := rhpv3.ValidateRegistryUpdate(oldEntry, entry, r.hostID); err != nil { + if err := rhp3.ValidateRegistryUpdate(oldEntry, entry, r.hostID); err != nil { return old, fmt.Errorf("invalid registry update: %w", err) } else if err = r.store.SetRegistryValue(entry, expirationHeight); err != nil { return old, fmt.Errorf("failed to update registry key: %w", err) @@ -115,7 +115,7 @@ func (r *Manager) Put(entry rhpv3.RegistryEntry, expirationHeight uint64) (rhpv3 // NewManager returns a new registry manager. func NewManager(privkey types.PrivateKey, store Store, log *zap.Logger) *Manager { m := &Manager{ - hostID: rhpv3.RegistryHostID(privkey.PublicKey()), + hostID: rhp3.RegistryHostID(privkey.PublicKey()), tg: threadgroup.New(), store: store, recorder: ®istryAccessRecorder{ diff --git a/host/registry/registry_test.go b/host/registry/registry_test.go index 85ceaad3..6e5e6f92 100644 --- a/host/registry/registry_test.go +++ b/host/registry/registry_test.go @@ -5,7 +5,7 @@ import ( "reflect" "testing" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/registry" "go.sia.tech/hostd/host/settings" @@ -14,10 +14,10 @@ import ( "lukechampine.com/frand" ) -func randomValue(key types.PrivateKey) (value rhpv3.RegistryEntry) { +func randomValue(key types.PrivateKey) (value rhp3.RegistryEntry) { value.Tweak = frand.Entropy256() value.Data = frand.Bytes(32) - value.Type = rhpv3.EntryTypeArbitrary + value.Type = rhp3.EntryTypeArbitrary value.PublicKey = key.PublicKey() value.Signature = key.SignHash(value.Hash()) return @@ -72,15 +72,15 @@ func TestRegistryPut(t *testing.T) { } // test updating the value's revision number and data; should succeed - entry := rhpv3.RegistryEntry{ - RegistryKey: rhpv3.RegistryKey{ + entry := rhp3.RegistryEntry{ + RegistryKey: rhp3.RegistryKey{ PublicKey: renterPriv.PublicKey(), Tweak: original.Tweak, }, - RegistryValue: rhpv3.RegistryValue{ + RegistryValue: rhp3.RegistryValue{ Data: original.Data, Revision: 1, - Type: rhpv3.EntryTypeArbitrary, + Type: rhp3.EntryTypeArbitrary, }, } entry.Signature = renterPriv.SignHash(entry.Hash()) @@ -92,19 +92,19 @@ func TestRegistryPut(t *testing.T) { } // test updating the value's work; should succeed - updatedEntry := rhpv3.RegistryEntry{ + updatedEntry := rhp3.RegistryEntry{ RegistryKey: entry.RegistryKey, RegistryValue: updated, } - entry = rhpv3.RegistryEntry{ + entry = rhp3.RegistryEntry{ RegistryKey: original.RegistryKey, - RegistryValue: rhpv3.RegistryValue{ + RegistryValue: rhp3.RegistryValue{ Data: make([]byte, 32), Revision: 1, - Type: rhpv3.EntryTypeArbitrary, + Type: rhp3.EntryTypeArbitrary, }, } - for rhpv3.CompareRegistryWork(entry, updatedEntry) <= 0 { + for rhp3.CompareRegistryWork(entry, updatedEntry) <= 0 { frand.Read(entry.Data) } entry.Signature = renterPriv.SignHash(entry.Hash()) @@ -116,13 +116,13 @@ func TestRegistryPut(t *testing.T) { } // test setting the value to a primary value; should succeed - hostID := rhpv3.RegistryHostID(hostPriv.PublicKey()) - entry = rhpv3.RegistryEntry{ + hostID := rhp3.RegistryHostID(hostPriv.PublicKey()) + entry = rhp3.RegistryEntry{ RegistryKey: original.RegistryKey, - RegistryValue: rhpv3.RegistryValue{ + RegistryValue: rhp3.RegistryValue{ Data: append([]byte(hostID[:20]), updated.Data...), Revision: 1, - Type: rhpv3.EntryTypePubKey, + Type: rhp3.EntryTypePubKey, }, } entry.Signature = renterPriv.SignHash(entry.Hash()) diff --git a/host/storage/storage.go b/host/storage/storage.go index 6c72a05f..205a9593 100644 --- a/host/storage/storage.go +++ b/host/storage/storage.go @@ -11,7 +11,7 @@ import ( lru "github.com/hashicorp/golang-lru/v2" "go.sia.tech/core/consensus" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.sia.tech/hostd/internal/threadgroup" @@ -84,7 +84,7 @@ type ( volumes map[int]*volume // changedVolumes tracks volumes that need to be fsynced changedVolumes map[int]bool - cache *lru.Cache[types.Hash256, *[rhpv2.SectorSize]byte] // Added cache + cache *lru.Cache[types.Hash256, *[rhp2.SectorSize]byte] // Added cache } ) @@ -128,7 +128,7 @@ func (vm *VolumeManager) lockVolume(id int) (func(), error) { // writeSector writes a sector to a volume. The volume is not synced after the // sector is written. The location is assumed to be empty and locked. -func (vm *VolumeManager) writeSector(data *[rhpv2.SectorSize]byte, loc SectorLocation) error { +func (vm *VolumeManager) writeSector(data *[rhp2.SectorSize]byte, loc SectorLocation) error { vol, err := vm.getVolume(loc.Volume) if err != nil { return fmt.Errorf("failed to get volume: %w", err) @@ -212,7 +212,7 @@ func (vm *VolumeManager) migrateSectors(locations []SectorLocation, force bool, return fmt.Errorf("failed to read sector: %w", err) } // calculate the returned root - root := rhpv2.SectorRoot(sector) + root := rhp2.SectorRoot(sector) if root != loc.Root { return fmt.Errorf("sector corrupt: %v != %v", loc.Root, root) } @@ -813,7 +813,7 @@ func (vm *VolumeManager) RemoveSector(root types.Hash256) error { } // zero the sector and immediately sync the volume - var zeroes [rhpv2.SectorSize]byte + var zeroes [rhp2.SectorSize]byte if err := vol.WriteSector(&zeroes, loc.Index); err != nil { return fmt.Errorf("failed to zero sector %v: %w", root, err) } else if err := vol.Sync(); err != nil { @@ -844,7 +844,7 @@ func (vm *VolumeManager) CacheStats() (hits, misses uint64) { } // Read reads the sector with the given root -func (vm *VolumeManager) Read(root types.Hash256) (*[rhpv2.SectorSize]byte, error) { +func (vm *VolumeManager) Read(root types.Hash256) (*[rhp2.SectorSize]byte, error) { done, err := vm.tg.Add() if err != nil { return nil, err @@ -915,7 +915,7 @@ func (vm *VolumeManager) Sync() error { // Write writes a sector to a volume. release should only be called after the // contract roots have been committed to prevent the sector from being deleted. -func (vm *VolumeManager) Write(root types.Hash256, data *[rhpv2.SectorSize]byte) (func() error, error) { +func (vm *VolumeManager) Write(root types.Hash256, data *[rhp2.SectorSize]byte) (func() error, error) { done, err := vm.tg.Add() if err != nil { return nil, err @@ -986,7 +986,7 @@ func (vm *VolumeManager) ProcessConsensusChange(cc modules.ConsensusChange) { // NewVolumeManager creates a new VolumeManager. func NewVolumeManager(vs VolumeStore, a Alerts, cm ChainManager, log *zap.Logger, sectorCacheSize uint32) (*VolumeManager, error) { // Initialize cache with LRU eviction and a max capacity of 64 - cache, err := lru.New[types.Hash256, *[rhpv2.SectorSize]byte](64) + cache, err := lru.New[types.Hash256, *[rhp2.SectorSize]byte](64) if err != nil { return nil, fmt.Errorf("failed to initialize cache: %w", err) } diff --git a/host/storage/storage_test.go b/host/storage/storage_test.go index d0f2d2f4..0e7777e7 100644 --- a/host/storage/storage_test.go +++ b/host/storage/storage_test.go @@ -9,7 +9,7 @@ import ( "path/filepath" "testing" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/alerts" "go.sia.tech/hostd/host/storage" @@ -81,9 +81,9 @@ func TestVolumeLoad(t *testing.T) { } // write a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { t.Fatal(err) @@ -129,7 +129,7 @@ func TestVolumeLoad(t *testing.T) { // write a new sector frand.Read(sector[:]) - root = rhpv2.SectorRoot(§or) + root = rhp2.SectorRoot(§or) release, err = vm.Write(root, §or) if err != nil { t.Fatal(err) @@ -255,11 +255,11 @@ func TestRemoveVolume(t *testing.T) { t.Fatal(err) } - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) // write the sector release, err := vm.Write(root, §or) @@ -344,11 +344,11 @@ func TestRemoveCorrupt(t *testing.T) { } for i := 0; i < 10; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) // write the sector release, err := vm.Write(root, §or) @@ -383,7 +383,7 @@ func TestRemoveCorrupt(t *testing.T) { defer f.Close() // corrupt a sector in the volume - n := rhpv2.SectorSize * frand.Intn(10) + n := rhp2.SectorSize * frand.Intn(10) f.WriteAt(frand.Bytes(512), int64(n)) if err := f.Sync(); err != nil { t.Fatal(err) @@ -458,11 +458,11 @@ func TestRemoveMissing(t *testing.T) { } for i := 0; i < 10; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) // write the sector release, err := vm.Write(root, §or) @@ -604,9 +604,9 @@ func TestVolumeDistribution(t *testing.T) { } writeSector := func() error { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:1024]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) _, err := vm.Write(root, §or) if err != nil { @@ -719,7 +719,7 @@ func TestVolumeGrow(t *testing.T) { volume = v.Volume // check the volume - if err := checkFileSize(volumeFilePath, int64(initialSectors*rhpv2.SectorSize)); err != nil { + if err := checkFileSize(volumeFilePath, int64(initialSectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } else if volume.TotalSectors != initialSectors { t.Fatalf("expected %v total sectors, got %v", initialSectors, volume.TotalSectors) @@ -730,11 +730,11 @@ func TestVolumeGrow(t *testing.T) { // fill the volume roots := make([]types.Hash256, 0, initialSectors) for i := 0; i < int(initialSectors); i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { t.Fatal(i, err) @@ -752,7 +752,7 @@ func TestVolumeGrow(t *testing.T) { } // check the volume - if err := checkFileSize(volumeFilePath, int64(newSectors*rhpv2.SectorSize)); err != nil { + if err := checkFileSize(volumeFilePath, int64(newSectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } @@ -773,11 +773,11 @@ func TestVolumeGrow(t *testing.T) { } defer f.Close() - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte for _, root := range roots { if _, err := io.ReadFull(f, sector[:]); err != nil { t.Fatal(err) - } else if rhpv2.SectorRoot(§or) != root { + } else if rhp2.SectorRoot(§or) != root { t.Fatal("sector was corrupted") } } @@ -838,7 +838,7 @@ func TestVolumeShrink(t *testing.T) { } // check the volume - if err := checkFileSize(volumeFilePath, int64(sectors*rhpv2.SectorSize)); err != nil { + if err := checkFileSize(volumeFilePath, int64(sectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } else if volume.TotalSectors != sectors { t.Fatalf("expected %v total sectors, got %v", sectors, volume.TotalSectors) @@ -849,11 +849,11 @@ func TestVolumeShrink(t *testing.T) { roots := make([]types.Hash256, 0, sectors) // fill the volume for i := 0; i < cap(roots); i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { t.Fatal(i, err) @@ -922,7 +922,7 @@ func TestVolumeShrink(t *testing.T) { t.Fatal(err) } else if err := <-result; err != nil { t.Fatal(err) - } else if err := checkFileSize(volumeFilePath, int64(remainingSectors*rhpv2.SectorSize)); err != nil { + } else if err := checkFileSize(volumeFilePath, int64(remainingSectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } @@ -1008,7 +1008,7 @@ func TestVolumeManagerReadWrite(t *testing.T) { t.Fatal(err) } - if err := checkFileSize(volumeFilePath, int64(sectors*rhpv2.SectorSize)); err != nil { + if err := checkFileSize(volumeFilePath, int64(sectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } else if volume.TotalSectors != sectors { t.Fatalf("expected %v total sectors, got %v", sectors, volume.TotalSectors) @@ -1019,11 +1019,11 @@ func TestVolumeManagerReadWrite(t *testing.T) { roots := make([]types.Hash256, 0, sectors) // fill the volume for i := 0; i < cap(roots); i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { t.Fatal(i, err) @@ -1052,7 +1052,7 @@ func TestVolumeManagerReadWrite(t *testing.T) { if err != nil { t.Fatal(err) } - retrievedRoot := rhpv2.SectorRoot(sector) + retrievedRoot := rhp2.SectorRoot(sector) if retrievedRoot != root { t.Fatalf("expected root %v, got %v", root, retrievedRoot) } @@ -1113,7 +1113,7 @@ func TestSectorCache(t *testing.T) { t.Fatal(err) } - if err := checkFileSize(volumeFilePath, int64(sectors*rhpv2.SectorSize)); err != nil { + if err := checkFileSize(volumeFilePath, int64(sectors*rhp2.SectorSize)); err != nil { t.Fatal(err) } else if volume.TotalSectors != sectors { t.Fatalf("expected %v total sectors, got %v", sectors, volume.TotalSectors) @@ -1124,11 +1124,11 @@ func TestSectorCache(t *testing.T) { roots := make([]types.Hash256, 0, sectors) // fill the volume for i := 0; i < cap(roots); i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte if _, err := frand.Read(sector[:256]); err != nil { t.Fatal(err) } - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { t.Fatal(i, err) @@ -1245,16 +1245,16 @@ func BenchmarkVolumeManagerWrite(b *testing.B) { b.Fatal(err) } - sectors := make([][rhpv2.SectorSize]byte, b.N) + sectors := make([][rhp2.SectorSize]byte, b.N) roots := make([]types.Hash256, b.N) for i := range sectors { frand.Read(sectors[i][:256]) - roots[i] = rhpv2.SectorRoot(§ors[i]) + roots[i] = rhp2.SectorRoot(§ors[i]) } b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) // fill the volume for i := 0; i < b.N; i++ { @@ -1308,7 +1308,7 @@ func BenchmarkNewVolume(b *testing.B) { b.ResetTimer() b.ReportMetric(float64(sectors), "sectors") - b.SetBytes(sectors * rhpv2.SectorSize) + b.SetBytes(sectors * rhp2.SectorSize) result := make(chan error, 1) for i := 0; i < b.N; i++ { @@ -1371,9 +1371,9 @@ func BenchmarkVolumeManagerRead(b *testing.B) { // fill the volume written := make([]types.Hash256, 0, b.N) for i := 0; i < b.N; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { b.Fatal(i, err) @@ -1385,7 +1385,7 @@ func BenchmarkVolumeManagerRead(b *testing.B) { b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) // read the sectors back for _, root := range written { if _, err := vm.Read(root); err != nil { @@ -1442,9 +1442,9 @@ func BenchmarkVolumeRemove(b *testing.B) { // fill the volume for i := 0; i < b.N; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) release, err := vm.Write(root, §or) if err != nil { b.Fatal(i, err) @@ -1464,7 +1464,7 @@ func BenchmarkVolumeRemove(b *testing.B) { b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) // migrate the sectors if err := vm.RemoveVolume(context.Background(), volume1.ID, false, result); err != nil { diff --git a/host/storage/volume.go b/host/storage/volume.go index f191fbac..2f9d1f4c 100644 --- a/host/storage/volume.go +++ b/host/storage/volume.go @@ -9,7 +9,7 @@ import ( "os" "sync" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "lukechampine.com/frand" ) @@ -90,12 +90,12 @@ func (v *volume) OpenVolume(localPath string, reload bool) error { } // ReadSector reads the sector at index from the volume -func (v *volume) ReadSector(index uint64) (*[rhpv2.SectorSize]byte, error) { +func (v *volume) ReadSector(index uint64) (*[rhp2.SectorSize]byte, error) { if v.data == nil { return nil, ErrVolumeNotAvailable } - var sector [rhpv2.SectorSize]byte - _, err := v.data.ReadAt(sector[:], int64(index*rhpv2.SectorSize)) + var sector [rhp2.SectorSize]byte + _, err := v.data.ReadAt(sector[:], int64(index*rhp2.SectorSize)) v.mu.Lock() if err != nil { v.stats.FailedReads++ @@ -108,11 +108,11 @@ func (v *volume) ReadSector(index uint64) (*[rhpv2.SectorSize]byte, error) { } // WriteSector writes a sector to the volume at index -func (v *volume) WriteSector(data *[rhpv2.SectorSize]byte, index uint64) error { +func (v *volume) WriteSector(data *[rhp2.SectorSize]byte, index uint64) error { if v.data == nil { panic("volume not open") // developer error } - _, err := v.data.WriteAt(data[:], int64(index*rhpv2.SectorSize)) + _, err := v.data.WriteAt(data[:], int64(index*rhp2.SectorSize)) v.mu.Lock() if err != nil { v.stats.FailedWrites++ @@ -155,16 +155,16 @@ func (v *volume) Resize(oldSectors, newSectors uint64) error { } if newSectors > oldSectors { - buf := make([]byte, rhpv2.SectorSize) + buf := make([]byte, rhp2.SectorSize) r := rand.New(rand.NewSource(int64(frand.Uint64n(math.MaxInt64)))) for i := oldSectors; i < newSectors; i++ { r.Read(buf) - if _, err := v.data.WriteAt(buf, int64(i*rhpv2.SectorSize)); err != nil { + if _, err := v.data.WriteAt(buf, int64(i*rhp2.SectorSize)); err != nil { return fmt.Errorf("failed to write sector to index %v: %w", i, err) } } } else { - if err := v.data.Truncate(int64(newSectors * rhpv2.SectorSize)); err != nil { + if err := v.data.Truncate(int64(newSectors * rhp2.SectorSize)); err != nil { return fmt.Errorf("failed to truncate volume: %w", err) } } diff --git a/internal/test/host.go b/internal/test/host.go index 95d51857..5bc54e30 100644 --- a/internal/test/host.go +++ b/internal/test/host.go @@ -8,8 +8,8 @@ import ( "path/filepath" "time" - crhpv2 "go.sia.tech/core/rhp/v2" - crhpv3 "go.sia.tech/core/rhp/v3" + crhp2 "go.sia.tech/core/rhp/v2" + crhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/accounts" "go.sia.tech/hostd/host/alerts" @@ -19,8 +19,8 @@ import ( "go.sia.tech/hostd/host/storage" "go.sia.tech/hostd/persist/sqlite" "go.sia.tech/hostd/rhp" - rhpv2 "go.sia.tech/hostd/rhp/v2" - rhpv3 "go.sia.tech/hostd/rhp/v3" + rhp2 "go.sia.tech/hostd/rhp/v2" + rhp3 "go.sia.tech/hostd/rhp/v3" "go.sia.tech/hostd/wallet" "go.uber.org/zap" ) @@ -46,9 +46,9 @@ type Host struct { accounts *accounts.AccountManager contracts *contracts.ContractManager - rhpv2 *rhpv2.SessionHandler - rhpv3 *rhpv3.SessionHandler - rhpv3WS net.Listener + rhp2 *rhp2.SessionHandler + rhp3 *rhp3.SessionHandler + rhp3WS net.Listener } // DefaultSettings returns the default settings for the test host @@ -77,9 +77,9 @@ var DefaultSettings = settings.Settings{ // Close shutsdown the host func (h *Host) Close() error { - h.rhpv3WS.Close() - h.rhpv2.Close() - h.rhpv3.Close() + h.rhp3WS.Close() + h.rhp2.Close() + h.rhp3.Close() h.settings.Close() h.wallet.Close() h.contracts.Close() @@ -90,19 +90,19 @@ func (h *Host) Close() error { return nil } -// RHPv2Addr returns the address of the RHPv2 listener -func (h *Host) RHPv2Addr() string { - return h.rhpv2.LocalAddr() +// RHP2Addr returns the address of the rhp2 listener +func (h *Host) RHP2Addr() string { + return h.rhp2.LocalAddr() } -// RHPv3Addr returns the address of the RHPv3 listener -func (h *Host) RHPv3Addr() string { - return h.rhpv3.LocalAddr() +// RHP3Addr returns the address of the rhp3 listener +func (h *Host) RHP3Addr() string { + return h.rhp3.LocalAddr() } -// RHPv3WSAddr returns the address of the RHPv3 WebSocket listener -func (h *Host) RHPv3WSAddr() string { - return h.rhpv3WS.Addr().String() +// RHP3WSAddr returns the address of the rhp3 WebSocket listener +func (h *Host) RHP3WSAddr() string { + return h.rhp3WS.Addr().String() } // AddVolume adds a new volume to the host @@ -119,14 +119,14 @@ func (h *Host) UpdateSettings(settings settings.Settings) error { return h.settings.UpdateSettings(settings) } -// RHPv2Settings returns the host's current RHPv2 settings -func (h *Host) RHPv2Settings() (crhpv2.HostSettings, error) { - return h.rhpv2.Settings() +// RHP2Settings returns the host's current rhp2 settings +func (h *Host) RHP2Settings() (crhp2.HostSettings, error) { + return h.rhp2.Settings() } -// RHPv3PriceTable returns the host's current RHPv3 price table -func (h *Host) RHPv3PriceTable() (crhpv3.HostPriceTable, error) { - return h.rhpv3.PriceTable() +// RHP3PriceTable returns the host's current rhp3 price table +func (h *Host) RHP3PriceTable() (crhp3.HostPriceTable, error) { + return h.rhp3.PriceTable() } // WalletAddress returns the host's wallet address @@ -213,30 +213,30 @@ func NewHost(privKey types.PrivateKey, dir string, node *Node, log *zap.Logger) sessions := rhp.NewSessionReporter() - rhpv2, err := rhpv2.NewSessionHandler(rhp2Listener, privKey, rhp3Listener.Addr().String(), node.cm, node.tp, wallet, contracts, settings, storage, stubDataMonitor{}, sessions, log.Named("rhpv2")) + rhp2, err := rhp2.NewSessionHandler(rhp2Listener, privKey, rhp3Listener.Addr().String(), node.cm, node.tp, wallet, contracts, settings, storage, stubDataMonitor{}, sessions, log.Named("rhp2")) if err != nil { - return nil, fmt.Errorf("failed to create rhpv2 session handler: %w", err) + return nil, fmt.Errorf("failed to create rhp2 session handler: %w", err) } - go rhpv2.Serve() + go rhp2.Serve() - rhpv3, err := rhpv3.NewSessionHandler(rhp3Listener, privKey, node.cm, node.tp, wallet, accounts, contracts, registry, storage, settings, stubDataMonitor{}, sessions, log.Named("rhpv3")) + rhp3, err := rhp3.NewSessionHandler(rhp3Listener, privKey, node.cm, node.tp, wallet, accounts, contracts, registry, storage, settings, stubDataMonitor{}, sessions, log.Named("rhp3")) if err != nil { - return nil, fmt.Errorf("failed to create rhpv3 session handler: %w", err) + return nil, fmt.Errorf("failed to create rhp3 session handler: %w", err) } - go rhpv3.Serve() + go rhp3.Serve() - rhpv3WSListener, err := net.Listen("tcp", "localhost:0") + rhp3WSListener, err := net.Listen("tcp", "localhost:0") if err != nil { return nil, fmt.Errorf("failed to create rhp3 websocket listener: %w", err) } go func() { - rhpv3WS := http.Server{ - Handler: rhpv3.WebSocketHandler(), + rhp3WS := http.Server{ + Handler: rhp3.WebSocketHandler(), ReadTimeout: 30 * time.Second, } - if err := rhpv3WS.Serve(rhpv3WSListener); err != nil { + if err := rhp3WS.Serve(rhp3WSListener); err != nil { return } }() @@ -253,8 +253,8 @@ func NewHost(privKey types.PrivateKey, dir string, node *Node, log *zap.Logger) accounts: accounts, contracts: contracts, - rhpv2: rhpv2, - rhpv3: rhpv3, - rhpv3WS: rhpv3WSListener, + rhp2: rhp2, + rhp3: rhp3, + rhp3WS: rhp3WSListener, }, nil } diff --git a/internal/test/renter.go b/internal/test/renter.go index 386278a2..b8e032f4 100644 --- a/internal/test/renter.go +++ b/internal/test/renter.go @@ -7,9 +7,9 @@ import ( "path/filepath" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" - rhpv3 "go.sia.tech/hostd/internal/test/rhp/v3" + rhp3 "go.sia.tech/hostd/internal/test/rhp/v3" "go.sia.tech/hostd/persist/sqlite" "go.sia.tech/hostd/wallet" "go.sia.tech/renterd/worker" @@ -55,7 +55,7 @@ func (r *Renter) NewRHP2Session(ctx context.Context, hostAddr string, hostKey ty return nil, err } - session := worker.NewSession(t, r.privKey, rhpv2.ContractRevision{}, rhpv2.HostSettings{}) + session := worker.NewSession(t, r.privKey, rhp2.ContractRevision{}, rhp2.HostSettings{}) ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() @@ -66,38 +66,38 @@ func (r *Renter) NewRHP2Session(ctx context.Context, hostAddr string, hostKey ty } // NewRHP3Session creates a new session -func (r *Renter) NewRHP3Session(ctx context.Context, hostAddr string, hostKey types.PublicKey) (*rhpv3.Session, error) { - return rhpv3.NewSession(ctx, hostKey, hostAddr, r.ChainManager(), r.Wallet()) +func (r *Renter) NewRHP3Session(ctx context.Context, hostAddr string, hostKey types.PublicKey) (*rhp3.Session, error) { + return rhp3.NewSession(ctx, hostKey, hostAddr, r.ChainManager(), r.Wallet()) } // Settings returns the host's current settings -func (r *Renter) Settings(ctx context.Context, hostAddr string, hostKey types.PublicKey) (rhpv2.HostSettings, error) { +func (r *Renter) Settings(ctx context.Context, hostAddr string, hostKey types.PublicKey) (rhp2.HostSettings, error) { t, err := dialTransport(ctx, hostAddr, hostKey) if err != nil { - return rhpv2.HostSettings{}, fmt.Errorf("failed to create session: %w", err) + return rhp2.HostSettings{}, fmt.Errorf("failed to create session: %w", err) } defer t.Close() settings, err := worker.RPCSettings(ctx, t) if err != nil { - return rhpv2.HostSettings{}, fmt.Errorf("failed to get settings: %w", err) + return rhp2.HostSettings{}, fmt.Errorf("failed to get settings: %w", err) } return settings, nil } // FormContract forms a contract with the host -func (r *Renter) FormContract(ctx context.Context, hostAddr string, hostKey types.PublicKey, renterPayout, hostCollateral types.Currency, duration uint64) (rhpv2.ContractRevision, error) { +func (r *Renter) FormContract(ctx context.Context, hostAddr string, hostKey types.PublicKey, renterPayout, hostCollateral types.Currency, duration uint64) (rhp2.ContractRevision, error) { t, err := dialTransport(ctx, hostAddr, hostKey) if err != nil { - return rhpv2.ContractRevision{}, fmt.Errorf("failed to dial transport: %w", err) + return rhp2.ContractRevision{}, fmt.Errorf("failed to dial transport: %w", err) } defer t.Close() settings, err := worker.RPCSettings(ctx, t) if err != nil { - return rhpv2.ContractRevision{}, fmt.Errorf("failed to get host settings: %w", err) + return rhp2.ContractRevision{}, fmt.Errorf("failed to get host settings: %w", err) } cs := r.TipState() - contract := rhpv2.PrepareContractFormation(r.privKey.PublicKey(), hostKey, renterPayout, hostCollateral, cs.Index.Height+duration, settings, r.WalletAddress()) - formationCost := rhpv2.ContractFormationCost(cs, contract, settings.ContractPrice) + contract := rhp2.PrepareContractFormation(r.privKey.PublicKey(), hostKey, renterPayout, hostCollateral, cs.Index.Height+duration, settings, r.WalletAddress()) + formationCost := rhp2.ContractFormationCost(cs, contract, settings.ContractPrice) feeEstimate := r.TPool().RecommendedFee().Mul64(2000) formationTxn := types.Transaction{ MinerFees: []types.Currency{feeEstimate}, @@ -107,17 +107,17 @@ func (r *Renter) FormContract(ctx context.Context, hostAddr string, hostKey type toSign, release, err := r.wallet.FundTransaction(&formationTxn, fundAmount) if err != nil { - return rhpv2.ContractRevision{}, fmt.Errorf("failed to fund transaction: %w", err) + return rhp2.ContractRevision{}, fmt.Errorf("failed to fund transaction: %w", err) } defer release() if err := r.wallet.SignTransaction(cs, &formationTxn, toSign, explicitCoveredFields(formationTxn)); err != nil { - return rhpv2.ContractRevision{}, fmt.Errorf("failed to sign transaction: %w", err) + return rhp2.ContractRevision{}, fmt.Errorf("failed to sign transaction: %w", err) } revision, _, err := worker.RPCFormContract(ctx, t, r.privKey, []types.Transaction{formationTxn}) if err != nil { - return rhpv2.ContractRevision{}, fmt.Errorf("failed to form contract: %w", err) + return rhp2.ContractRevision{}, fmt.Errorf("failed to form contract: %w", err) } return revision, nil } @@ -134,7 +134,7 @@ func (r *Renter) PublicKey() types.PublicKey { // dialTransport is a convenience function that connects to the specified // host -func dialTransport(ctx context.Context, hostIP string, hostKey types.PublicKey) (_ *rhpv2.Transport, err error) { +func dialTransport(ctx context.Context, hostIP string, hostKey types.PublicKey) (_ *rhp2.Transport, err error) { conn, err := (&net.Dialer{}).DialContext(ctx, "tcp", hostIP) if err != nil { return nil, err @@ -154,7 +154,7 @@ func dialTransport(ctx context.Context, hostIP string, hostKey types.PublicKey) } }() - t, err := rhpv2.NewRenterTransport(conn, hostKey) + t, err := rhp2.NewRenterTransport(conn, hostKey) if err != nil { conn.Close() return nil, err diff --git a/persist/sqlite/registry.go b/persist/sqlite/registry.go index 09b9bb1d..bdffe5c0 100644 --- a/persist/sqlite/registry.go +++ b/persist/sqlite/registry.go @@ -6,13 +6,13 @@ import ( "fmt" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/hostd/host/registry" ) // GetRegistryValue returns the registry value for the given key. If the key is not // found should return ErrEntryNotFound. -func (s *Store) GetRegistryValue(key rhpv3.RegistryKey) (entry rhpv3.RegistryValue, _ error) { +func (s *Store) GetRegistryValue(key rhp3.RegistryKey) (entry rhp3.RegistryValue, _ error) { err := s.queryRow(`SELECT revision_number, entry_type, entry_data, entry_signature FROM registry_entries WHERE registry_key=$1`, sqlHash256(key.Hash())).Scan( (*sqlUint64)(&entry.Revision), &entry.Type, @@ -20,15 +20,15 @@ func (s *Store) GetRegistryValue(key rhpv3.RegistryKey) (entry rhpv3.RegistryVal (*sqlHash512)(&entry.Signature), ) if errors.Is(err, sql.ErrNoRows) { - return rhpv3.RegistryValue{}, registry.ErrEntryNotFound + return rhp3.RegistryValue{}, registry.ErrEntryNotFound } else if err != nil { - return rhpv3.RegistryValue{}, fmt.Errorf("failed to get registry entry: %w", err) + return rhp3.RegistryValue{}, fmt.Errorf("failed to get registry entry: %w", err) } return } // SetRegistryValue sets the registry value for the given key. -func (s *Store) SetRegistryValue(entry rhpv3.RegistryEntry, expiration uint64) error { +func (s *Store) SetRegistryValue(entry rhp3.RegistryEntry, expiration uint64) error { const ( selectQuery = `SELECT registry_key FROM registry_entries re WHERE re.registry_key=$1` insertQuery = `INSERT INTO registry_entries (registry_key, revision_number, entry_type, entry_signature, entry_data, expiration_height) VALUES ($1, $2, $3, $4, $5, $6) RETURNING registry_key` diff --git a/rhp/v2/contracts.go b/rhp/v2/contracts.go index cf02dca6..4b236828 100644 --- a/rhp/v2/contracts.go +++ b/rhp/v2/contracts.go @@ -4,7 +4,7 @@ import ( "errors" "fmt" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/contracts" ) @@ -78,33 +78,33 @@ var ( // validateWriteActions validates the actions received by the renter for the // write RPC and estimates the cost of completing the actions. -func validateWriteActions(actions []rhpv2.RPCWriteAction, oldSectors uint64, proof bool, remainingDuration uint64, settings rhpv2.HostSettings) (rpcCost, error) { +func validateWriteActions(actions []rhp2.RPCWriteAction, oldSectors uint64, proof bool, remainingDuration uint64, settings rhp2.HostSettings) (rpcCost, error) { var uploadBytes uint64 newSectors := oldSectors for _, action := range actions { switch action.Type { - case rhpv2.RPCWriteActionAppend: - if len(action.Data) != rhpv2.SectorSize { + case rhp2.RPCWriteActionAppend: + if len(action.Data) != rhp2.SectorSize { return rpcCost{}, fmt.Errorf("invalid sector size: %v: %w", len(action.Data), ErrInvalidSectorLength) } newSectors++ - uploadBytes += rhpv2.SectorSize - case rhpv2.RPCWriteActionTrim: + uploadBytes += rhp2.SectorSize + case rhp2.RPCWriteActionTrim: if action.A > newSectors { return rpcCost{}, ErrTrimOutOfBounds } newSectors -= action.A - case rhpv2.RPCWriteActionSwap: + case rhp2.RPCWriteActionSwap: if action.A >= newSectors || action.B >= newSectors { return rpcCost{}, ErrSwapOutOfBounds } - case rhpv2.RPCWriteActionUpdate: + case rhp2.RPCWriteActionUpdate: idx, offset := action.A, action.B if idx >= newSectors { return rpcCost{}, ErrUpdateOutOfBounds - } else if offset+uint64(len(action.Data)) > rhpv2.SectorSize { + } else if offset+uint64(len(action.Data)) > rhp2.SectorSize { return rpcCost{}, ErrOffsetOutOfBounds - } else if proof && (offset%rhpv2.LeafSize != 0) || len(action.Data)%rhpv2.LeafSize != 0 { + } else if proof && (offset%rhp2.LeafSize != 0) || len(action.Data)%rhp2.LeafSize != 0 { return rpcCost{}, ErrUpdateProofSize } default: @@ -119,8 +119,8 @@ func validateWriteActions(actions []rhpv2.RPCWriteAction, oldSectors uint64, pro if newSectors > oldSectors { additionalSectors := (newSectors - oldSectors) - cost.Storage = settings.StoragePrice.Mul64(rhpv2.SectorSize * additionalSectors * remainingDuration) // cost of storing the new sectors - cost.Collateral = settings.Collateral.Mul64(rhpv2.SectorSize * additionalSectors * remainingDuration) // collateral for the new sectors + cost.Storage = settings.StoragePrice.Mul64(rhp2.SectorSize * additionalSectors * remainingDuration) // cost of storing the new sectors + cost.Collateral = settings.Collateral.Mul64(rhp2.SectorSize * additionalSectors * remainingDuration) // collateral for the new sectors } if proof { @@ -131,24 +131,24 @@ func validateWriteActions(actions []rhpv2.RPCWriteAction, oldSectors uint64, pro return cost, nil } -func validateReadActions(sections []rhpv2.RPCReadRequestSection, proof bool, settings rhpv2.HostSettings) (rpcCost, error) { +func validateReadActions(sections []rhp2.RPCReadRequestSection, proof bool, settings rhp2.HostSettings) (rpcCost, error) { // validate the request sections and calculate the cost var bandwidth uint64 for _, sec := range sections { switch { - case uint64(sec.Offset)+uint64(sec.Length) > rhpv2.SectorSize: + case uint64(sec.Offset)+uint64(sec.Length) > rhp2.SectorSize: return rpcCost{}, ErrOffsetOutOfBounds case sec.Length == 0: return rpcCost{}, errors.New("length cannot be zero") - case proof && (sec.Offset%rhpv2.LeafSize != 0 || sec.Length%rhpv2.LeafSize != 0): + case proof && (sec.Offset%rhp2.LeafSize != 0 || sec.Length%rhp2.LeafSize != 0): return rpcCost{}, errors.New("offset and length must be multiples of SegmentSize when requesting a Merkle proof") } bandwidth += uint64(sec.Length) if proof { - start := sec.Offset / rhpv2.LeafSize - end := (sec.Offset + sec.Length) / rhpv2.LeafSize - proofSize := rhpv2.RangeProofSize(rhpv2.LeavesPerSector, start, end) + start := sec.Offset / rhp2.LeafSize + end := (sec.Offset + sec.Length) / rhp2.LeafSize + proofSize := rhp2.RangeProofSize(rhp2.LeavesPerSector, start, end) bandwidth += proofSize * 32 } } @@ -159,8 +159,8 @@ func validateReadActions(sections []rhpv2.RPCReadRequestSection, proof bool, set }, nil } -func rpcSectorRootsCost(count, offset uint64, settings rhpv2.HostSettings) rpcCost { - proofSize := rhpv2.RangeProofSize(rhpv2.LeavesPerSector, offset, offset+count) +func rpcSectorRootsCost(count, offset uint64, settings rhp2.HostSettings) rpcCost { + proofSize := rhp2.RangeProofSize(rhp2.LeavesPerSector, offset, offset+count) return rpcCost{ Base: settings.BaseRPCPrice, Egress: settings.DownloadBandwidthPrice.Mul64((count + proofSize) * 32), @@ -176,7 +176,7 @@ func contractUnlockConditions(hostKey, renterKey types.UnlockKey) types.UnlockCo // validateContractFormation verifies that the new contract is valid given the // host's settings. -func validateContractFormation(fc types.FileContract, hostKey, renterKey types.UnlockKey, currentHeight uint64, settings rhpv2.HostSettings) (types.Currency, error) { +func validateContractFormation(fc types.FileContract, hostKey, renterKey types.UnlockKey, currentHeight uint64, settings rhp2.HostSettings) (types.Currency, error) { switch { case fc.Filesize != 0: return types.ZeroCurrency, errors.New("initial filesize should be 0") @@ -217,7 +217,7 @@ func validateContractFormation(fc types.FileContract, hostKey, renterKey types.U // validateContractRenewal verifies that the renewed contract is valid given the // old contract. A renewal is valid if the contract fields match and the // revision number is 0. -func validateContractRenewal(existing types.FileContractRevision, renewal types.FileContract, hostKey, renterKey types.UnlockKey, baseHostRevenue, baseRiskedCollateral types.Currency, currentHeight uint64, settings rhpv2.HostSettings) (storageRevenue, riskedCollateral, lockedCollateral types.Currency, err error) { +func validateContractRenewal(existing types.FileContractRevision, renewal types.FileContract, hostKey, renterKey types.UnlockKey, baseHostRevenue, baseRiskedCollateral types.Currency, currentHeight uint64, settings rhp2.HostSettings) (storageRevenue, riskedCollateral, lockedCollateral types.Currency, err error) { switch { case renewal.RevisionNumber != 0: return types.ZeroCurrency, types.ZeroCurrency, types.ZeroCurrency, errors.New("revision number must be zero") diff --git a/rhp/v2/rhp.go b/rhp/v2/rhp.go index 74c28481..b693c6ae 100644 --- a/rhp/v2/rhp.go +++ b/rhp/v2/rhp.go @@ -9,7 +9,7 @@ import ( "time" "go.sia.tech/core/consensus" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/contracts" "go.sia.tech/hostd/host/settings" @@ -55,9 +55,9 @@ type ( // Write writes a sector to persistent storage. release should only be // called after the contract roots have been committed to prevent the // sector from being deleted. - Write(root types.Hash256, data *[rhpv2.SectorSize]byte) (release func() error, _ error) + Write(root types.Hash256, data *[rhp2.SectorSize]byte) (release func() error, _ error) // Read reads the sector with the given root from the manager. - Read(root types.Hash256) (*[rhpv2.SectorSize]byte, error) + Read(root types.Hash256) (*[rhp2.SectorSize]byte, error) // Sync syncs the data files of changed volumes. Sync() error } @@ -128,14 +128,14 @@ func (sh *SessionHandler) rpcLoop(sess *session, log *zap.Logger) error { } rpcFn, ok := map[types.Specifier]func(*session, *zap.Logger) (contracts.Usage, error){ - rhpv2.RPCFormContractID: sh.rpcFormContract, - rhpv2.RPCRenewClearContractID: sh.rpcRenewAndClearContract, - rhpv2.RPCLockID: sh.rpcLock, - rhpv2.RPCUnlockID: sh.rpcUnlock, - rhpv2.RPCSectorRootsID: sh.rpcSectorRoots, - rhpv2.RPCReadID: sh.rpcRead, - rhpv2.RPCSettingsID: sh.rpcSettings, - rhpv2.RPCWriteID: sh.rpcWrite, + rhp2.RPCFormContractID: sh.rpcFormContract, + rhp2.RPCRenewClearContractID: sh.rpcRenewAndClearContract, + rhp2.RPCLockID: sh.rpcLock, + rhp2.RPCUnlockID: sh.rpcUnlock, + rhp2.RPCSectorRootsID: sh.rpcSectorRoots, + rhp2.RPCReadID: sh.rpcRead, + rhp2.RPCSettingsID: sh.rpcSettings, + rhp2.RPCWriteID: sh.rpcWrite, }[id] if !ok { err = fmt.Errorf("unknown RPC ID %q", id) @@ -162,7 +162,7 @@ func (sh *SessionHandler) upgrade(conn net.Conn) error { ingressLimiter, egressLimiter := sh.settings.BandwidthLimiters() rhpConn := rhp.NewConn(conn, sh.monitor, ingressLimiter, egressLimiter) - t, err := rhpv2.NewHostTransport(rhpConn, sh.privateKey) + t, err := rhp2.NewHostTransport(rhpConn, sh.privateKey) if err != nil { return err } @@ -199,11 +199,11 @@ func (sh *SessionHandler) Close() error { } // Settings returns the host's current settings -func (sh *SessionHandler) Settings() (rhpv2.HostSettings, error) { +func (sh *SessionHandler) Settings() (rhp2.HostSettings, error) { settings := sh.settings.Settings() usedSectors, totalSectors, err := sh.storage.Usage() if err != nil { - return rhpv2.HostSettings{}, fmt.Errorf("failed to get storage usage: %w", err) + return rhp2.HostSettings{}, fmt.Errorf("failed to get storage usage: %w", err) } netaddr := settings.NetAddress @@ -212,10 +212,10 @@ func (sh *SessionHandler) Settings() (rhpv2.HostSettings, error) { } // if the net address is still empty, return an error if len(netaddr) == 0 { - return rhpv2.HostSettings{}, errors.New("no net address found") + return rhp2.HostSettings{}, errors.New("no net address found") } - return rhpv2.HostSettings{ + return rhp2.HostSettings{ // protocol version Version: Version, @@ -223,13 +223,13 @@ func (sh *SessionHandler) Settings() (rhpv2.HostSettings, error) { Address: sh.wallet.Address(), SiaMuxPort: sh.rhp3Port, NetAddress: netaddr, - TotalStorage: totalSectors * rhpv2.SectorSize, - RemainingStorage: (totalSectors - usedSectors) * rhpv2.SectorSize, + TotalStorage: totalSectors * rhp2.SectorSize, + RemainingStorage: (totalSectors - usedSectors) * rhp2.SectorSize, // network defaults MaxDownloadBatchSize: defaultBatchSize, MaxReviseBatchSize: defaultBatchSize, - SectorSize: rhpv2.SectorSize, + SectorSize: rhp2.SectorSize, WindowSize: settings.WindowSize, // contract formation @@ -266,7 +266,7 @@ func (sh *SessionHandler) Serve() error { go func() { defer conn.Close() if err := sh.upgrade(conn); err != nil { - if errors.Is(err, rhpv2.ErrRenterClosed) || errors.Is(err, io.EOF) { + if errors.Is(err, rhp2.ErrRenterClosed) || errors.Is(err, io.EOF) { // skip logging graceful close and EOF errors return } diff --git a/rhp/v2/rpc.go b/rhp/v2/rpc.go index ca26a01e..3ecbdee4 100644 --- a/rhp/v2/rpc.go +++ b/rhp/v2/rpc.go @@ -9,7 +9,7 @@ import ( "math" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/contracts" "go.sia.tech/hostd/rhp" @@ -47,13 +47,13 @@ func (sh *SessionHandler) rpcSettings(s *session, log *zap.Logger) (contracts.Us s.t.WriteResponseErr(ErrHostInternalError) return contracts.Usage{}, fmt.Errorf("failed to marshal settings: %v", err) } - return contracts.Usage{}, s.writeResponse(&rhpv2.RPCSettingsResponse{ + return contracts.Usage{}, s.writeResponse(&rhp2.RPCSettingsResponse{ Settings: js, }, 30*time.Second) } func (sh *SessionHandler) rpcLock(s *session, log *zap.Logger) (contracts.Usage, error) { - var req rhpv2.RPCLockRequest + var req rhp2.RPCLockRequest if err := s.readRequest(&req, minMessageSize, 30*time.Second); err != nil { return contracts.Usage{}, err } @@ -86,7 +86,7 @@ func (sh *SessionHandler) rpcLock(s *session, log *zap.Logger) (contracts.Usage, // set the contract s.contract = contract - lockResp := &rhpv2.RPCLockResponse{ + lockResp := &rhp2.RPCLockResponse{ Acquired: true, NewChallenge: newChallenge, Revision: contract.Revision, @@ -118,7 +118,7 @@ func (sh *SessionHandler) rpcFormContract(s *session, log *zap.Logger) (contract s.t.WriteResponseErr(ErrNotAcceptingContracts) return contracts.Usage{}, ErrNotAcceptingContracts } - var req rhpv2.RPCFormContractRequest + var req rhp2.RPCFormContractRequest if err := s.readRequest(&req, 10*minMessageSize, time.Minute); err != nil { return contracts.Usage{}, err } @@ -170,7 +170,7 @@ func (sh *SessionHandler) rpcFormContract(s *session, log *zap.Logger) (contract hostSig := sh.privateKey.SignHash(sigHash) // send the host's transaction funding additions to the renter - hostAdditionsResp := &rhpv2.RPCFormContractAdditions{ + hostAdditionsResp := &rhp2.RPCFormContractAdditions{ Inputs: formationTxn.SiacoinInputs[renterInputs:], Outputs: formationTxn.SiacoinOutputs[renterOutputs:], } @@ -179,7 +179,7 @@ func (sh *SessionHandler) rpcFormContract(s *session, log *zap.Logger) (contract } // read and validate the renter's signatures - var renterSignaturesResp rhpv2.RPCFormContractSignatures + var renterSignaturesResp rhp2.RPCFormContractSignatures if err := s.readResponse(&renterSignaturesResp, 10*minMessageSize, 30*time.Second); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renter signatures: %w", err) } else if err := validateRenterRevisionSignature(renterSignaturesResp.RevisionSignature, initialRevision.ParentID, sigHash, renterPub); err != nil { @@ -217,7 +217,7 @@ func (sh *SessionHandler) rpcFormContract(s *session, log *zap.Logger) (contract } // send the host signatures to the renter - hostSignaturesResp := &rhpv2.RPCFormContractSignatures{ + hostSignaturesResp := &rhp2.RPCFormContractSignatures{ ContractSignatures: formationTxn.Signatures[renterTxnSigs:], RevisionSignature: types.TransactionSignature{ ParentID: types.Hash256(formationTxn.FileContractID(0)), @@ -250,7 +250,7 @@ func (sh *SessionHandler) rpcRenewAndClearContract(s *session, log *zap.Logger) return contracts.Usage{}, err } - var req rhpv2.RPCRenewAndClearContractRequest + var req rhp2.RPCRenewAndClearContractRequest if err := s.readRequest(&req, 10*minMessageSize, time.Minute); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renew request: %w", err) } @@ -328,7 +328,7 @@ func (sh *SessionHandler) rpcRenewAndClearContract(s *session, log *zap.Logger) defer discard() // send the renter the host additions to the renewal txn - hostAdditionsResp := &rhpv2.RPCFormContractAdditions{ + hostAdditionsResp := &rhp2.RPCFormContractAdditions{ Inputs: renewalTxn.SiacoinInputs[renterInputs:], Outputs: renewalTxn.SiacoinOutputs[renterOutputs:], } @@ -337,7 +337,7 @@ func (sh *SessionHandler) rpcRenewAndClearContract(s *session, log *zap.Logger) } // read the renter's signatures for the renewal - var renterSigsResp rhpv2.RPCRenewAndClearContractSignatures + var renterSigsResp rhp2.RPCRenewAndClearContractSignatures if err = s.readResponse(&renterSigsResp, minMessageSize, 30*time.Second); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renter signatures: %w", err) } else if len(renterSigsResp.RevisionSignature.Signature) != 64 { @@ -398,7 +398,7 @@ func (sh *SessionHandler) rpcRenewAndClearContract(s *session, log *zap.Logger) } // send the host signatures to the renter - hostSigsResp := &rhpv2.RPCRenewAndClearContractSignatures{ + hostSigsResp := &rhp2.RPCRenewAndClearContractSignatures{ ContractSignatures: renewalTxn.Signatures[len(renterSigsResp.ContractSignatures):], RevisionSignature: signedRenewal.Signatures()[0], FinalRevisionSignature: signedClearing.HostSignature, @@ -415,7 +415,7 @@ func (sh *SessionHandler) rpcSectorRoots(s *session, log *zap.Logger) (contracts return contracts.Usage{}, err } - var req rhpv2.RPCSectorRootsRequest + var req rhp2.RPCSectorRootsRequest if err := s.readRequest(&req, minMessageSize, 30*time.Second); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read sector roots request: %w", err) } @@ -495,9 +495,9 @@ func (sh *SessionHandler) rpcSectorRoots(s *session, log *zap.Logger) (contracts } s.contract = signedRevision - sectorRootsResp := &rhpv2.RPCSectorRootsResponse{ + sectorRootsResp := &rhp2.RPCSectorRootsResponse{ SectorRoots: roots, - MerkleProof: rhpv2.BuildSectorRangeProof(roots, req.RootOffset, req.RootOffset+req.NumRoots), + MerkleProof: rhp2.BuildSectorRangeProof(roots, req.RootOffset, req.RootOffset+req.NumRoots), Signature: hostSig, } return usage, s.writeResponse(sectorRootsResp, 2*time.Minute) @@ -517,14 +517,14 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage return contracts.Usage{}, fmt.Errorf("failed to get settings: %w", err) } - var req rhpv2.RPCWriteRequest - if err := s.readRequest(&req, 5*rhpv2.SectorSize, 5*time.Minute); err != nil { + var req rhp2.RPCWriteRequest + if err := s.readRequest(&req, 5*rhp2.SectorSize, 5*time.Minute); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read write request: %w", err) } remainingDuration := uint64(s.contract.Revision.WindowEnd) - currentHeight // validate the requested actions - oldSectors := s.contract.Revision.Filesize / rhpv2.SectorSize + oldSectors := s.contract.Revision.Filesize / rhp2.SectorSize costs, err := validateWriteActions(req.Actions, oldSectors, req.MerkleProof, remainingDuration, settings) if err != nil { err := fmt.Errorf("failed to validate write actions: %w", err) @@ -558,14 +558,14 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage oldRoots := contractUpdater.SectorRoots() for _, action := range req.Actions { switch action.Type { - case rhpv2.RPCWriteActionAppend: - if len(action.Data) != rhpv2.SectorSize { + case rhp2.RPCWriteActionAppend: + if len(action.Data) != rhp2.SectorSize { err := fmt.Errorf("append action: invalid sector size: %v", len(action.Data)) s.t.WriteResponseErr(err) return contracts.Usage{}, err } - sector := (*[rhpv2.SectorSize]byte)(action.Data) - root := rhpv2.SectorRoot(sector) + sector := (*[rhp2.SectorSize]byte)(action.Data) + root := rhp2.SectorRoot(sector) release, err := sh.storage.Write(root, sector) if err != nil { err := fmt.Errorf("append action: failed to write sector: %w", err) @@ -574,19 +574,19 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage } defer release() contractUpdater.AppendSector(root) - case rhpv2.RPCWriteActionTrim: + case rhp2.RPCWriteActionTrim: if err := contractUpdater.TrimSectors(action.A); err != nil { err := fmt.Errorf("trim action: failed to trim sectors: %w", err) s.t.WriteResponseErr(err) return contracts.Usage{}, err } - case rhpv2.RPCWriteActionSwap: + case rhp2.RPCWriteActionSwap: if err := contractUpdater.SwapSectors(action.A, action.B); err != nil { err := fmt.Errorf("swap action: failed to swap sectors: %w", err) s.t.WriteResponseErr(err) return contracts.Usage{}, err } - case rhpv2.RPCWriteActionUpdate: + case rhp2.RPCWriteActionUpdate: root, err := contractUpdater.SectorRoot(action.A) if err != nil { err := fmt.Errorf("update action: failed to get sector root: %w", err) @@ -601,18 +601,18 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage } i, offset := action.A, action.B - if offset > rhpv2.SectorSize { + if offset > rhp2.SectorSize { err := fmt.Errorf("update action: invalid offset %v bytes", offset) s.t.WriteResponseErr(err) return contracts.Usage{}, err - } else if offset+uint64(len(action.Data)) > rhpv2.SectorSize { + } else if offset+uint64(len(action.Data)) > rhp2.SectorSize { err := errors.New("update action: offset + data exceeds sector size") s.t.WriteResponseErr(err) return contracts.Usage{}, err } copy(sector[offset:], action.Data) - newRoot := rhpv2.SectorRoot(sector) + newRoot := rhp2.SectorRoot(sector) if err := contractUpdater.UpdateSector(newRoot, i); err != nil { err := fmt.Errorf("update action: failed to update sector: %w", err) @@ -630,11 +630,11 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage } // build the merkle proof response - writeResp := &rhpv2.RPCWriteMerkleProof{ + writeResp := &rhp2.RPCWriteMerkleProof{ NewMerkleRoot: contractUpdater.MerkleRoot(), } if req.MerkleProof { - writeResp.OldSubtreeHashes, writeResp.OldLeafHashes = rhpv2.BuildDiffProof(req.Actions, oldRoots) + writeResp.OldSubtreeHashes, writeResp.OldLeafHashes = rhp2.BuildDiffProof(req.Actions, oldRoots) } if err := s.writeResponse(writeResp, time.Minute); err != nil { return contracts.Usage{}, fmt.Errorf("failed to write merkle proof: %w", err) @@ -642,10 +642,10 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage // apply the new merkle root and file size to the revision revision.FileMerkleRoot = writeResp.NewMerkleRoot - revision.Filesize = contractUpdater.SectorCount() * rhpv2.SectorSize + revision.Filesize = contractUpdater.SectorCount() * rhp2.SectorSize // read the renter's signature - var renterSigResponse rhpv2.RPCWriteResponse + var renterSigResponse rhp2.RPCWriteResponse if err := s.readResponse(&renterSigResponse, minMessageSize, 30*time.Second); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renter signature: %w", err) } @@ -690,7 +690,7 @@ func (sh *SessionHandler) rpcWrite(s *session, log *zap.Logger) (contracts.Usage s.contract = signedRevision // send the host signature - hostSigResp := &rhpv2.RPCWriteResponse{Signature: hostSig} + hostSigResp := &rhp2.RPCWriteResponse{Signature: hostSig} return usage, s.writeResponse(hostSigResp, 30*time.Second) } @@ -711,7 +711,7 @@ func (sh *SessionHandler) rpcRead(s *session, log *zap.Logger) (contracts.Usage, } // read the read request - var req rhpv2.RPCReadRequest + var req rhp2.RPCReadRequest if err := s.readRequest(&req, 4*minMessageSize, time.Minute); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read read request: %w", err) } @@ -784,7 +784,7 @@ func (sh *SessionHandler) rpcRead(s *session, log *zap.Logger) (contracts.Usage, err := s.readResponse(&id, minMessageSize, 5*time.Minute) if err != nil { stopSignal <- err - } else if id != rhpv2.RPCReadStop { + } else if id != rhp2.RPCReadStop { stopSignal <- errors.New("expected 'stop' from renter, got " + id.String()) } else { stopSignal <- nil @@ -800,13 +800,13 @@ func (sh *SessionHandler) rpcRead(s *session, log *zap.Logger) (contracts.Usage, return usage, err } - resp := &rhpv2.RPCReadResponse{ + resp := &rhp2.RPCReadResponse{ Data: sector[sec.Offset : sec.Offset+sec.Length], } if req.MerkleProof { - start := sec.Offset / rhpv2.LeafSize - end := (sec.Offset + sec.Length) / rhpv2.LeafSize - resp.MerkleProof = rhpv2.BuildProof(sector, start, end, nil) + start := sec.Offset / rhp2.LeafSize + end := (sec.Offset + sec.Length) / rhp2.LeafSize + resp.MerkleProof = rhp2.BuildProof(sector, start, end, nil) } // check for the stop signal and send the response diff --git a/rhp/v2/rpc_test.go b/rhp/v2/rpc_test.go index 84bf5191..fd42ad66 100644 --- a/rhp/v2/rpc_test.go +++ b/rhp/v2/rpc_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/internal/test" "go.sia.tech/renterd/wallet" @@ -26,12 +26,12 @@ func TestSettings(t *testing.T) { defer renter.Close() defer host.Close() - hostSettings, err := host.RHPv2Settings() + hostSettings, err := host.RHP2Settings() if err != nil { t.Fatal(err) } - renterSettings, err := renter.Settings(context.Background(), host.RHPv2Addr(), host.PublicKey()) + renterSettings, err := renter.Settings(context.Background(), host.RHP2Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } else if !reflect.DeepEqual(hostSettings, renterSettings) { @@ -49,21 +49,21 @@ func TestUploadDownload(t *testing.T) { defer host.Close() // form a contract - contract, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) + contract, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) if err != nil { t.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), contract.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), contract.ID()) if err != nil { t.Fatal(err) } defer session.Close() // generate a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - sectorRoot := rhpv2.SectorRoot(§or) + sectorRoot := rhp2.SectorRoot(§or) // calculate the remaining duration of the contract var remainingDuration uint64 @@ -74,7 +74,7 @@ func TestUploadDownload(t *testing.T) { } // upload the sector remainingDuration = contractExpiration - currentHeight - price, collateral := rhpv2.RPCAppendCost(session.Settings(), remainingDuration) + price, collateral := rhp2.RPCAppendCost(session.Settings(), remainingDuration) writtenRoot, err := session.Append(context.Background(), §or, price, collateral) if err != nil { t.Fatal(err) @@ -83,7 +83,7 @@ func TestUploadDownload(t *testing.T) { } // check the host's sector roots matches the sector we just uploaded - price = rhpv2.RPCSectorRootsCost(session.Settings(), 1) + price = rhp2.RPCSectorRootsCost(session.Settings(), 1) roots, err := session.SectorRoots(context.Background(), 0, 1, price) if err != nil { t.Fatal(err) @@ -94,21 +94,21 @@ func TestUploadDownload(t *testing.T) { // check that the revision fields are correct revision := session.Revision().Revision switch { - case revision.Filesize != rhpv2.SectorSize: + case revision.Filesize != rhp2.SectorSize: t.Fatal("wrong filesize") case revision.FileMerkleRoot != sectorRoot: t.Fatal("wrong merkle root") } - sections := []rhpv2.RPCReadRequestSection{ + sections := []rhp2.RPCReadRequestSection{ { MerkleRoot: writtenRoot, Offset: 0, - Length: rhpv2.SectorSize, + Length: rhp2.SectorSize, }, } - price = rhpv2.RPCReadCost(session.Settings(), sections) + price = rhp2.RPCReadCost(session.Settings(), sections) var buf bytes.Buffer ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) @@ -134,12 +134,12 @@ func TestRenew(t *testing.T) { t.Run("empty contract", func(t *testing.T) { state := renter.TipState() // form a contract - origin, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) + origin, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) if err != nil { t.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), origin.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), origin.ID()) if err != nil { t.Fatal(err) } @@ -154,13 +154,13 @@ func TestRenew(t *testing.T) { renewHeight := origin.Revision.WindowEnd + 10 settings := session.Settings() current := session.Revision().Revision - additionalCollateral := rhpv2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) - renewed, basePrice := rhpv2.PrepareContractRenewal(current, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) + additionalCollateral := rhp2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) + renewed, basePrice := rhp2.PrepareContractRenewal(current, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) renewalTxn := types.Transaction{ FileContracts: []types.FileContract{renewed}, } - cost := rhpv2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) + cost := rhp2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) toSign, discard, err := renter.Wallet().FundTransaction(&renewalTxn, cost) if err != nil { t.Fatal(err) @@ -216,21 +216,21 @@ func TestRenew(t *testing.T) { t.Run("drained contract", func(t *testing.T) { // form a contract state := renter.TipState() - origin, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) + origin, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) if err != nil { t.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), origin.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), origin.ID()) if err != nil { t.Fatal(err) } defer session.Close() // generate a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - sectorRoot := rhpv2.SectorRoot(§or) + sectorRoot := rhp2.SectorRoot(§or) // calculate the remaining duration of the contract var remainingDuration uint64 @@ -241,7 +241,7 @@ func TestRenew(t *testing.T) { } // upload the sector remainingDuration = contractExpiration - currentHeight - _, collateral := rhpv2.RPCAppendCost(session.Settings(), remainingDuration) + _, collateral := rhp2.RPCAppendCost(session.Settings(), remainingDuration) // overpay for the sector, leaving a few hastings for the renewal remainingValue := types.NewCurrency64(25) price := origin.Revision.ValidRenterPayout().Sub(remainingValue) @@ -261,13 +261,13 @@ func TestRenew(t *testing.T) { settings := session.Settings() renewHeight := origin.Revision.WindowEnd + 10 current := session.Revision().Revision - additionalCollateral := rhpv2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) - renewed, basePrice := rhpv2.PrepareContractRenewal(session.Revision().Revision, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) + additionalCollateral := rhp2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) + renewed, basePrice := rhp2.PrepareContractRenewal(session.Revision().Revision, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) renewalTxn := types.Transaction{ FileContracts: []types.FileContract{renewed}, } - cost := rhpv2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) + cost := rhp2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) toSign, discard, err := renter.Wallet().FundTransaction(&renewalTxn, cost) if err != nil { t.Fatal(err) @@ -286,7 +286,7 @@ func TestRenew(t *testing.T) { } // previous session was closed by the RPC failure, create a new one - session, err = renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), origin.ID()) + session, err = renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), origin.ID()) if err != nil { t.Fatal(err) } @@ -330,21 +330,21 @@ func TestRenew(t *testing.T) { t.Run("non-empty contract", func(t *testing.T) { // form a contract state := renter.TipState() - origin, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) + origin, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) if err != nil { t.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), origin.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), origin.ID()) if err != nil { t.Fatal(err) } defer session.Close() // generate a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - sectorRoot := rhpv2.SectorRoot(§or) + sectorRoot := rhp2.SectorRoot(§or) // calculate the remaining duration of the contract var remainingDuration uint64 @@ -355,7 +355,7 @@ func TestRenew(t *testing.T) { } // upload the sector remainingDuration = contractExpiration - currentHeight - price, collateral := rhpv2.RPCAppendCost(session.Settings(), remainingDuration) + price, collateral := rhp2.RPCAppendCost(session.Settings(), remainingDuration) writtenRoot, err := session.Append(context.Background(), §or, price, collateral) if err != nil { t.Fatal(err) @@ -372,13 +372,13 @@ func TestRenew(t *testing.T) { settings := session.Settings() renewHeight := origin.Revision.WindowEnd + 10 current := session.Revision().Revision - additionalCollateral := rhpv2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) - renewed, basePrice := rhpv2.PrepareContractRenewal(session.Revision().Revision, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) + additionalCollateral := rhp2.ContractRenewalCollateral(current.FileContract, 1<<22, settings, renter.TipState().Index.Height, renewHeight) + renewed, basePrice := rhp2.PrepareContractRenewal(session.Revision().Revision, renter.WalletAddress(), types.Siacoins(10), additionalCollateral, host.PublicKey(), settings, renewHeight) renewalTxn := types.Transaction{ FileContracts: []types.FileContract{renewed}, } - cost := rhpv2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) + cost := rhp2.ContractRenewalCost(state, renewed, settings.ContractPrice, types.ZeroCurrency, basePrice) toSign, discard, err := renter.Wallet().FundTransaction(&renewalTxn, cost) if err != nil { t.Fatal(err) @@ -435,12 +435,12 @@ func BenchmarkUpload(b *testing.B) { defer host.Close() // form a contract - contract, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) + contract, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) if err != nil { b.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), contract.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), contract.ID()) if err != nil { b.Fatal(err) } @@ -455,17 +455,17 @@ func BenchmarkUpload(b *testing.B) { } // calculate the cost of uploading a sector remainingDuration = contractExpiration - currentHeight - price, collateral := rhpv2.RPCAppendCost(session.Settings(), remainingDuration) + price, collateral := rhp2.RPCAppendCost(session.Settings(), remainingDuration) // generate b.N sectors - sectors := make([][rhpv2.SectorSize]byte, b.N) + sectors := make([][rhp2.SectorSize]byte, b.N) for i := range sectors { frand.Read(sectors[i][:256]) } b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) // upload b.N sectors for i := 0; i < b.N; i++ { @@ -492,7 +492,7 @@ func BenchmarkDownload(b *testing.B) { } // form a contract - contract, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) + contract, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) if err != nil { b.Fatal(err) } @@ -502,7 +502,7 @@ func BenchmarkDownload(b *testing.B) { b.Fatal(err) } - session, err := renter.NewRHP2Session(context.Background(), host.RHPv2Addr(), host.PublicKey(), contract.ID()) + session, err := renter.NewRHP2Session(context.Background(), host.RHP2Addr(), host.PublicKey(), contract.ID()) if err != nil { b.Fatal(err) } @@ -521,11 +521,11 @@ func BenchmarkDownload(b *testing.B) { // upload b.N sectors for i := 0; i < b.N; i++ { // generate a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) // upload the sector - price, collateral := rhpv2.RPCAppendCost(session.Settings(), remainingDuration) + price, collateral := rhp2.RPCAppendCost(session.Settings(), remainingDuration) root, err := session.Append(context.Background(), §or, price, collateral) if err != nil { b.Fatal(err) @@ -535,16 +535,16 @@ func BenchmarkDownload(b *testing.B) { b.ReportAllocs() b.ResetTimer() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) for _, root := range uploaded { // download the sector - sections := []rhpv2.RPCReadRequestSection{{ + sections := []rhp2.RPCReadRequestSection{{ MerkleRoot: root, Offset: 0, - Length: rhpv2.SectorSize, + Length: rhp2.SectorSize, }} - price := rhpv2.RPCReadCost(session.Settings(), sections) + price := rhp2.RPCReadCost(session.Settings(), sections) if err := session.Read(context.Background(), io.Discard, sections, price); err != nil { b.Fatal(err) } diff --git a/rhp/v2/session.go b/rhp/v2/session.go index 5a814e57..0e39b1c7 100644 --- a/rhp/v2/session.go +++ b/rhp/v2/session.go @@ -3,7 +3,7 @@ package rhp import ( "time" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "go.sia.tech/core/types" "go.sia.tech/hostd/host/contracts" "go.sia.tech/hostd/rhp" @@ -18,22 +18,22 @@ const minMessageSize = 4096 type session struct { id rhp.UID conn *rhp.Conn - t *rhpv2.Transport + t *rhp2.Transport contract contracts.SignedRevision } -func (s *session) readRequest(req rhpv2.ProtocolObject, maxSize uint64, timeout time.Duration) error { +func (s *session) readRequest(req rhp2.ProtocolObject, maxSize uint64, timeout time.Duration) error { s.conn.SetReadDeadline(time.Now().Add(timeout)) return s.t.ReadRequest(req, maxSize) } -func (s *session) readResponse(req rhpv2.ProtocolObject, maxSize uint64, timeout time.Duration) error { +func (s *session) readResponse(req rhp2.ProtocolObject, maxSize uint64, timeout time.Duration) error { s.conn.SetReadDeadline(time.Now().Add(timeout)) return s.t.ReadResponse(req, maxSize) } -func (s *session) writeResponse(resp rhpv2.ProtocolObject, timeout time.Duration) error { +func (s *session) writeResponse(resp rhp2.ProtocolObject, timeout time.Duration) error { s.conn.SetWriteDeadline(time.Now().Add(timeout)) return s.t.WriteResponse(resp) } diff --git a/rhp/v3/contracts.go b/rhp/v3/contracts.go index 04f1f7a4..02951e38 100644 --- a/rhp/v3/contracts.go +++ b/rhp/v3/contracts.go @@ -4,7 +4,7 @@ import ( "errors" "fmt" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" ) @@ -19,7 +19,7 @@ func hashFinalRevision(clearing types.FileContractRevision, renewal types.FileCo // validateContractRenewal verifies that the renewed contract is valid given the // old contract. A renewal is valid if the contract fields match and the // revision number is 0. -func validateContractRenewal(existing types.FileContractRevision, renewal types.FileContract, hostKey, renterKey types.UnlockKey, walletAddress types.Address, baseStorageRevenue, baseRiskedCollateral types.Currency, pt rhpv3.HostPriceTable) (riskedCollateral, lockedCollateral types.Currency, err error) { +func validateContractRenewal(existing types.FileContractRevision, renewal types.FileContract, hostKey, renterKey types.UnlockKey, walletAddress types.Address, baseStorageRevenue, baseRiskedCollateral types.Currency, pt rhp3.HostPriceTable) (riskedCollateral, lockedCollateral types.Currency, err error) { switch { case renewal.RevisionNumber != 0: return types.ZeroCurrency, types.ZeroCurrency, errors.New("revision number must be zero") diff --git a/rhp/v3/execute.go b/rhp/v3/execute.go index 299caa3c..32499667 100644 --- a/rhp/v3/execute.go +++ b/rhp/v3/execute.go @@ -10,8 +10,8 @@ import ( "strings" "time" - rhpv2 "go.sia.tech/core/rhp/v2" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp2 "go.sia.tech/core/rhp/v2" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/accounts" "go.sia.tech/hostd/host/contracts" @@ -32,12 +32,12 @@ type ( programExecutor struct { hostKey types.PrivateKey - instructions []rhpv3.Instruction + instructions []rhp3.Instruction programData programData - priceTable rhpv3.HostPriceTable + priceTable rhp3.HostPriceTable budget *accounts.Budget - cost rhpv3.ResourceCost + cost rhp3.ResourceCost usage accounts.Usage revision *contracts.SignedRevision @@ -63,8 +63,8 @@ var ( ErrContractRequired = errors.New("contract required") ) -func (pe *programExecutor) instructionOutput(output []byte, proof []types.Hash256, err error) rhpv3.RPCExecuteProgramResponse { - resp := rhpv3.RPCExecuteProgramResponse{ +func (pe *programExecutor) instructionOutput(output []byte, proof []types.Hash256, err error) rhp3.RPCExecuteProgramResponse { + resp := rhp3.RPCExecuteProgramResponse{ AdditionalCollateral: pe.cost.Collateral, TotalCost: pe.cost.Base.Add(pe.cost.Storage).Add(pe.cost.Egress).Add(pe.cost.Ingress), FailureRefund: pe.cost.Storage, @@ -75,12 +75,12 @@ func (pe *programExecutor) instructionOutput(output []byte, proof []types.Hash25 } if pe.updater != nil { resp.NewMerkleRoot = pe.updater.MerkleRoot() - resp.NewSize = pe.updater.SectorCount() * rhpv2.SectorSize + resp.NewSize = pe.updater.SectorCount() * rhp2.SectorSize } return resp } -func (pe *programExecutor) payForExecution(cost rhpv3.ResourceCost, usage accounts.Usage) error { +func (pe *programExecutor) payForExecution(cost rhp3.ResourceCost, usage accounts.Usage) error { if err := pe.budget.Spend(usage); err != nil { return err } @@ -89,11 +89,14 @@ func (pe *programExecutor) payForExecution(cost rhpv3.ResourceCost, usage accoun return nil } -func (pe *programExecutor) executeAppendSector(instr *rhpv3.InstrAppendSector, log *zap.Logger) ([]byte, []types.Hash256, error) { - root, sector, err := pe.programData.Sector(instr.SectorDataOffset) +func (pe *programExecutor) executeAppendSector(instr *rhp3.InstrAppendSector, log *zap.Logger) ([]byte, []types.Hash256, error) { + sector, err := pe.programData.Sector(instr.SectorDataOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read sector: %w", err) } + rootCalcStart := time.Now() + root := rhp2.SectorRoot(sector) + log.Debug("calculated sector root", zap.Duration("duration", time.Since(rootCalcStart))) // pay for execution cost := pe.priceTable.AppendSectorCost(pe.remainingDuration) if err := pe.payForExecution(cost, costToAccountUsage(cost)); err != nil { @@ -113,12 +116,12 @@ func (pe *programExecutor) executeAppendSector(instr *rhpv3.InstrAppendSector, l proofStart := time.Now() roots := pe.updater.SectorRoots() - proof, _ := rhpv2.BuildDiffProof([]rhpv2.RPCWriteAction{{Type: rhpv2.RPCWriteActionAppend}}, roots[:len(roots)-1]) // TODO: add rhp3 proof methods + proof, _ := rhp2.BuildDiffProof([]rhp2.RPCWriteAction{{Type: rhp2.RPCWriteActionAppend}}, roots[:len(roots)-1]) // TODO: add rhp3 proof methods log.Debug("built proof", zap.Duration("duration", time.Since(proofStart))) return nil, proof, nil } -func (pe *programExecutor) executeAppendSectorRoot(instr *rhpv3.InstrAppendSectorRoot, log *zap.Logger) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeAppendSectorRoot(instr *rhp3.InstrAppendSectorRoot, log *zap.Logger) ([]byte, []types.Hash256, error) { root, err := pe.programData.Hash(instr.MerkleRootOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read sector root: %w", err) @@ -141,12 +144,12 @@ func (pe *programExecutor) executeAppendSectorRoot(instr *rhpv3.InstrAppendSecto } proofStart := time.Now() roots := pe.updater.SectorRoots() - proof, _ := rhpv2.BuildDiffProof([]rhpv2.RPCWriteAction{{Type: rhpv2.RPCWriteActionAppend}}, roots[:len(roots)-1]) // TODO: add rhp3 proof methods + proof, _ := rhp2.BuildDiffProof([]rhp2.RPCWriteAction{{Type: rhp2.RPCWriteActionAppend}}, roots[:len(roots)-1]) // TODO: add rhp3 proof methods log.Debug("built proof", zap.Duration("duration", time.Since(proofStart))) return nil, proof, nil } -func (pe *programExecutor) executeDropSectors(instr *rhpv3.InstrDropSectors, log *zap.Logger) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeDropSectors(instr *rhp3.InstrDropSectors, log *zap.Logger) ([]byte, []types.Hash256, error) { count, err := pe.programData.Uint64(instr.SectorCountOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read sector count: %w", err) @@ -161,7 +164,7 @@ func (pe *programExecutor) executeDropSectors(instr *rhpv3.InstrDropSectors, log var proof []types.Hash256 if instr.ProofRequired { proofStart := time.Now() - proof = rhpv2.BuildSectorRangeProof(pe.updater.SectorRoots(), pe.updater.SectorCount()-count, pe.updater.SectorCount()) // TODO: add rhp3 proof methods + proof = rhp2.BuildSectorRangeProof(pe.updater.SectorRoots(), pe.updater.SectorCount()-count, pe.updater.SectorCount()) // TODO: add rhp3 proof methods log.Debug("built proof", zap.Duration("duration", time.Since(proofStart))) } @@ -172,7 +175,7 @@ func (pe *programExecutor) executeDropSectors(instr *rhpv3.InstrDropSectors, log return nil, proof, nil } -func (pe *programExecutor) executeHasSector(instr *rhpv3.InstrHasSector) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeHasSector(instr *rhp3.InstrHasSector) ([]byte, []types.Hash256, error) { root, err := pe.programData.Hash(instr.MerkleRootOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read sector root: %w", err) @@ -199,7 +202,7 @@ func (pe *programExecutor) executeHasSector(instr *rhpv3.InstrHasSector) ([]byte return output, nil, nil } -func (pe *programExecutor) executeReadOffset(instr *rhpv3.InstrReadOffset, log *zap.Logger) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeReadOffset(instr *rhp3.InstrReadOffset, log *zap.Logger) ([]byte, []types.Hash256, error) { offset, err := pe.programData.Uint64(instr.OffsetOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read offset: %w", err) @@ -214,8 +217,8 @@ func (pe *programExecutor) executeReadOffset(instr *rhpv3.InstrReadOffset, log * return nil, nil, fmt.Errorf("failed to pay for instruction: %w", err) } - sectorIndex := offset / rhpv2.SectorSize - relOffset := offset % rhpv2.SectorSize + sectorIndex := offset / rhp2.SectorSize + relOffset := offset % rhp2.SectorSize root, err := pe.updater.SectorRoot(sectorIndex) if err != nil { @@ -233,14 +236,14 @@ func (pe *programExecutor) executeReadOffset(instr *rhpv3.InstrReadOffset, log * } proofStartTime := time.Now() - proofStart := relOffset / rhpv2.LeafSize - proofEnd := (relOffset + length) / rhpv2.LeafSize - proof := rhpv2.BuildProof(sector, proofStart, proofEnd, nil) + proofStart := relOffset / rhp2.LeafSize + proofEnd := (relOffset + length) / rhp2.LeafSize + proof := rhp2.BuildProof(sector, proofStart, proofEnd, nil) log.Debug("built proof", zap.Duration("duration", time.Since(proofStartTime))) return sector[relOffset : relOffset+length], proof, nil } -func (pe *programExecutor) executeReadSector(instr *rhpv3.InstrReadSector, log *zap.Logger) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeReadSector(instr *rhp3.InstrReadSector, log *zap.Logger) ([]byte, []types.Hash256, error) { root, err := pe.programData.Hash(instr.MerkleRootOffset) if err != nil { return nil, nil, fmt.Errorf("failed to read sector root: %w", err) @@ -258,10 +261,10 @@ func (pe *programExecutor) executeReadSector(instr *rhpv3.InstrReadSector, log * switch { case length == 0: return nil, nil, fmt.Errorf("read length cannot be 0") - case offset+length > rhpv2.SectorSize: + case offset+length > rhp2.SectorSize: return nil, nil, fmt.Errorf("read length %v is out of bounds", length) - case instr.ProofRequired && (offset%rhpv2.LeafSize != 0 || length%rhpv2.LeafSize != 0): - return nil, nil, fmt.Errorf("read offset (%d) and length (%d) must be multiples of %d", offset, length, rhpv2.LeafSize) + case instr.ProofRequired && (offset%rhp2.LeafSize != 0 || length%rhp2.LeafSize != 0): + return nil, nil, fmt.Errorf("read offset (%d) and length (%d) must be multiples of %d", offset, length, rhp2.LeafSize) } // pay for execution @@ -281,14 +284,14 @@ func (pe *programExecutor) executeReadSector(instr *rhpv3.InstrReadSector, log * } proofStartTime := time.Now() - proofStart := offset / rhpv2.LeafSize - proofEnd := (offset + length) / rhpv2.LeafSize - proof := rhpv2.BuildProof(sector, proofStart, proofEnd, nil) + proofStart := offset / rhp2.LeafSize + proofEnd := (offset + length) / rhp2.LeafSize + proof := rhp2.BuildProof(sector, proofStart, proofEnd, nil) log.Debug("built proof", zap.Duration("duration", time.Since(proofStartTime))) return sector[offset : offset+length], proof, nil } -func (pe *programExecutor) executeSwapSector(instr *rhpv3.InstrSwapSector, log *zap.Logger) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeSwapSector(instr *rhp3.InstrSwapSector, log *zap.Logger) ([]byte, []types.Hash256, error) { // read the swap params a, err := pe.programData.Uint64(instr.Sector1Offset) if err != nil { @@ -313,7 +316,7 @@ func (pe *programExecutor) executeSwapSector(instr *rhpv3.InstrSwapSector, log * proofStart := time.Now() var oldLeafHashes []types.Hash256 // build the proof before updating the roots - proof, oldLeafHashes = rhpv2.BuildDiffProof([]rhpv2.RPCWriteAction{{Type: rhpv2.RPCWriteActionSwap, A: a, B: b}}, pe.updater.SectorRoots()) // TODO: add rhp3 proof methods + proof, oldLeafHashes = rhp2.BuildDiffProof([]rhp2.RPCWriteAction{{Type: rhp2.RPCWriteActionSwap, A: a, B: b}}, pe.updater.SectorRoots()) // TODO: add rhp3 proof methods // encode the old leaf hashes var buf bytes.Buffer enc := types.NewEncoder(&buf) @@ -334,7 +337,7 @@ func (pe *programExecutor) executeSwapSector(instr *rhpv3.InstrSwapSector, log * return output, proof, nil } -func (pe *programExecutor) executeUpdateSector(instr *rhpv3.InstrUpdateSector) ([]byte, []types.Hash256, error) { +func (pe *programExecutor) executeUpdateSector(instr *rhp3.InstrUpdateSector, log *zap.Logger) ([]byte, []types.Hash256, error) { offset, length := instr.Offset, instr.Length // read the patch patch, err := pe.programData.Bytes(instr.DataOffset, length) @@ -348,8 +351,8 @@ func (pe *programExecutor) executeUpdateSector(instr *rhpv3.InstrUpdateSector) ( return nil, nil, fmt.Errorf("failed to pay for instruction: %w", err) } - sectorIndex := offset / rhpv2.SectorSize - relOffset := offset % rhpv2.SectorSize + sectorIndex := offset / rhp2.SectorSize + relOffset := offset % rhp2.SectorSize oldRoot, err := pe.updater.SectorRoot(sectorIndex) if err != nil { @@ -362,13 +365,13 @@ func (pe *programExecutor) executeUpdateSector(instr *rhpv3.InstrUpdateSector) ( } // validate and apply the patch - if relOffset+length > rhpv2.SectorSize { + if relOffset+length > rhp2.SectorSize { return nil, nil, fmt.Errorf("update offset %v length %v is out of bounds", relOffset, length) } copy(sector[relOffset:], patch) // store the new sector - newRoot := rhpv2.SectorRoot((*[rhpv2.SectorSize]byte)(sector)) + newRoot := rhp2.SectorRoot((*[rhp2.SectorSize]byte)(sector)) release, err := pe.storage.Write(newRoot, sector) if err != nil { return nil, nil, fmt.Errorf("failed to write sector: %w", err) @@ -380,11 +383,14 @@ func (pe *programExecutor) executeUpdateSector(instr *rhpv3.InstrUpdateSector) ( return newRoot[:], nil, nil } -func (pe *programExecutor) executeStoreSector(instr *rhpv3.InstrStoreSector) ([]byte, error) { - root, sector, err := pe.programData.Sector(instr.DataOffset) +func (pe *programExecutor) executeStoreSector(instr *rhp3.InstrStoreSector, log *zap.Logger) ([]byte, error) { + sector, err := pe.programData.Sector(instr.DataOffset) if err != nil { return nil, fmt.Errorf("failed to read sector: %w", err) } + rootCalcStart := time.Now() + root := rhp2.SectorRoot(sector) + log.Debug("calculated sector root", zap.Duration("duration", time.Since(rootCalcStart))) // pay for execution cost := pe.priceTable.StoreSectorCost(instr.Duration) @@ -413,7 +419,7 @@ func (pe *programExecutor) executeStoreSector(instr *rhpv3.InstrStoreSector) ([] return root[:], nil } -func (pe *programExecutor) executeRevision(instr *rhpv3.InstrRevision) ([]byte, error) { +func (pe *programExecutor) executeRevision(instr *rhp3.InstrRevision) ([]byte, error) { // pay for execution cost := pe.priceTable.RevisionCost() if err := pe.payForExecution(cost, costToAccountUsage(cost)); err != nil { @@ -433,7 +439,7 @@ func (pe *programExecutor) executeRevision(instr *rhpv3.InstrRevision) ([]byte, return buf.Bytes(), nil } -func (pe *programExecutor) executeReadRegistry(instr *rhpv3.InstrReadRegistry) ([]byte, error) { +func (pe *programExecutor) executeReadRegistry(instr *rhp3.InstrReadRegistry) ([]byte, error) { if instr.Version != readRegistryNoType && instr.Version != readRegistryType { return nil, fmt.Errorf("unsupported registry version: %v", instr.Version) } @@ -465,7 +471,7 @@ func (pe *programExecutor) executeReadRegistry(instr *rhpv3.InstrReadRegistry) ( return nil, fmt.Errorf("failed to pay for instruction: %w", err) } - key := rhpv3.RegistryKey{ + key := rhp3.RegistryKey{ PublicKey: publicKey, Tweak: tweak, } @@ -489,7 +495,7 @@ func (pe *programExecutor) executeReadRegistry(instr *rhpv3.InstrReadRegistry) ( return buf.Bytes(), nil } -func (pe *programExecutor) executeUpdateRegistry(instr *rhpv3.InstrUpdateRegistry) ([]byte, error) { +func (pe *programExecutor) executeUpdateRegistry(instr *rhp3.InstrUpdateRegistry) ([]byte, error) { tweak, err := pe.programData.Hash(instr.TweakOffset) if err != nil { return nil, fmt.Errorf("failed to read tweak: %w", err) @@ -529,12 +535,12 @@ func (pe *programExecutor) executeUpdateRegistry(instr *rhpv3.InstrUpdateRegistr return nil, fmt.Errorf("failed to pay for instruction: %w", err) } - value := rhpv3.RegistryEntry{ - RegistryKey: rhpv3.RegistryKey{ + value := rhp3.RegistryEntry{ + RegistryKey: rhp3.RegistryKey{ PublicKey: publicKey, Tweak: tweak, }, - RegistryValue: rhpv3.RegistryValue{ + RegistryValue: rhp3.RegistryValue{ Revision: revision, Type: instr.EntryType, Data: data, @@ -553,8 +559,8 @@ func (pe *programExecutor) executeUpdateRegistry(instr *rhpv3.InstrUpdateRegistr return nil, nil } -func (pe *programExecutor) executeProgram(ctx context.Context) <-chan rhpv3.RPCExecuteProgramResponse { - outputs := make(chan rhpv3.RPCExecuteProgramResponse, len(pe.instructions)) +func (pe *programExecutor) executeProgram(ctx context.Context) <-chan rhp3.RPCExecuteProgramResponse { + outputs := make(chan rhp3.RPCExecuteProgramResponse, len(pe.instructions)) go func() { defer close(outputs) @@ -574,34 +580,34 @@ func (pe *programExecutor) executeProgram(ctx context.Context) <-chan rhpv3.RPCE start := time.Now() // execute the instruction switch instr := instruction.(type) { - case *rhpv3.InstrAppendSector: + case *rhp3.InstrAppendSector: output, proof, err = pe.executeAppendSector(instr, log) - case *rhpv3.InstrAppendSectorRoot: + case *rhp3.InstrAppendSectorRoot: output, proof, err = pe.executeAppendSectorRoot(instr, log) - case *rhpv3.InstrDropSectors: + case *rhp3.InstrDropSectors: output, proof, err = pe.executeDropSectors(instr, log) - case *rhpv3.InstrHasSector: + case *rhp3.InstrHasSector: output, proof, err = pe.executeHasSector(instr) - case *rhpv3.InstrReadOffset: + case *rhp3.InstrReadOffset: output, proof, err = pe.executeReadOffset(instr, log) - case *rhpv3.InstrReadSector: + case *rhp3.InstrReadSector: output, proof, err = pe.executeReadSector(instr, log) - case *rhpv3.InstrSwapSector: + case *rhp3.InstrSwapSector: output, proof, err = pe.executeSwapSector(instr, log) - case *rhpv3.InstrUpdateSector: - output, proof, err = pe.executeUpdateSector(instr) - case *rhpv3.InstrStoreSector: - output, err = pe.executeStoreSector(instr) - case *rhpv3.InstrRevision: + case *rhp3.InstrUpdateSector: + output, proof, err = pe.executeUpdateSector(instr, log) + case *rhp3.InstrStoreSector: + output, err = pe.executeStoreSector(instr, log) + case *rhp3.InstrRevision: output, err = pe.executeRevision(instr) - case *rhpv3.InstrReadRegistry: + case *rhp3.InstrReadRegistry: output, err = pe.executeReadRegistry(instr) - case *rhpv3.InstrReadRegistryNoVersion: + case *rhp3.InstrReadRegistryNoVersion: instr.Version = 1 // override the version output, err = pe.executeReadRegistry(&instr.InstrReadRegistry) - case *rhpv3.InstrUpdateRegistry: + case *rhp3.InstrUpdateRegistry: output, err = pe.executeUpdateRegistry(instr) - case *rhpv3.InstrUpdateRegistryNoType: + case *rhp3.InstrUpdateRegistryNoType: output, err = pe.executeUpdateRegistry(&instr.InstrUpdateRegistry) default: // immediately return an error if the instruction is unknown @@ -659,7 +665,7 @@ func (pe *programExecutor) rollback() error { return nil } -func (pe *programExecutor) commit(s *rhpv3.Stream) error { +func (pe *programExecutor) commit(s *rhp3.Stream) error { if pe.committed { panic("commit called multiple times") } @@ -688,7 +694,7 @@ func (pe *programExecutor) commit(s *rhpv3.Stream) error { start := time.Now() // read the finalize request - var req rhpv3.RPCFinalizeProgramRequest + var req rhp3.RPCFinalizeProgramRequest if err := s.ReadResponse(&req, maxRequestSize); err != nil { return fmt.Errorf("failed to read finalize request: %w", err) } @@ -711,7 +717,7 @@ func (pe *programExecutor) commit(s *rhpv3.Stream) error { // update the size and root of the contract revision.FileMerkleRoot = pe.updater.MerkleRoot() - revision.Filesize = rhpv2.SectorSize * pe.updater.SectorCount() + revision.Filesize = rhp2.SectorSize * pe.updater.SectorCount() // verify the renter signature sigHash := rhp.HashRevision(revision) @@ -739,7 +745,7 @@ func (pe *programExecutor) commit(s *rhpv3.Stream) error { } // send the signature to the renter - resp := rhpv3.RPCFinalizeProgramResponse{ + resp := rhp3.RPCFinalizeProgramResponse{ Signature: signedRevision.HostSignature, } if err := s.WriteResponse(&resp); err != nil { @@ -763,14 +769,13 @@ func (pe *programExecutor) commit(s *rhpv3.Stream) error { } // Sector returns a sector and its root from the program's data. -func (pd programData) Sector(offset uint64) (types.Hash256, *[rhpv2.SectorSize]byte, error) { - if offset+rhpv2.SectorSize > uint64(len(pd)) { - return types.Hash256{}, nil, fmt.Errorf("sector offset %v is out of bounds", offset) +func (pd programData) Sector(offset uint64) (*[rhp2.SectorSize]byte, error) { + if offset+rhp2.SectorSize > uint64(len(pd)) { + return nil, fmt.Errorf("sector offset %v is out of bounds", offset) } - sector := (*[rhpv2.SectorSize]byte)(pd[offset : offset+rhpv2.SectorSize]) - root := rhpv2.SectorRoot(sector) - return root, sector, nil + sector := (*[rhp2.SectorSize]byte)(pd[offset : offset+rhp2.SectorSize]) + return sector, nil } // Bytes returns a slice of bytes from the program's data. @@ -816,7 +821,7 @@ func (pd programData) Signature(offset uint64) (types.Signature, error) { } // Execute executes the program's instructions -func (pe *programExecutor) Execute(ctx context.Context, s *rhpv3.Stream) error { +func (pe *programExecutor) Execute(ctx context.Context, s *rhp3.Stream) error { // create a cancellation context to stop the executeProgram goroutine ctx, cancel := context.WithCancel(ctx) defer cancel() @@ -852,7 +857,7 @@ func (pe *programExecutor) Usage() (usage contracts.Usage) { return usage } -func (sh *SessionHandler) newExecutor(instructions []rhpv3.Instruction, data []byte, pt rhpv3.HostPriceTable, budget *accounts.Budget, revision *contracts.SignedRevision, finalize bool, log *zap.Logger) (*programExecutor, error) { +func (sh *SessionHandler) newExecutor(instructions []rhp3.Instruction, data []byte, pt rhp3.HostPriceTable, budget *accounts.Budget, revision *contracts.SignedRevision, finalize bool, log *zap.Logger) (*programExecutor, error) { ex := &programExecutor{ hostKey: sh.privateKey, @@ -882,38 +887,38 @@ func (sh *SessionHandler) newExecutor(instructions []rhpv3.Instruction, data []b return ex, nil } -func instrLabel(instr rhpv3.Instruction) string { +func instrLabel(instr rhp3.Instruction) string { switch instr.(type) { - case *rhpv3.InstrAppendSector: + case *rhp3.InstrAppendSector: return "AppendSector" - case *rhpv3.InstrAppendSectorRoot: + case *rhp3.InstrAppendSectorRoot: return "AppendSectorRoot" - case *rhpv3.InstrDropSectors: + case *rhp3.InstrDropSectors: return "DropSectors" - case *rhpv3.InstrHasSector: + case *rhp3.InstrHasSector: return "HasSector" - case *rhpv3.InstrReadOffset: + case *rhp3.InstrReadOffset: return "ReadOffset" - case *rhpv3.InstrReadSector: + case *rhp3.InstrReadSector: return "ReadSector" - case *rhpv3.InstrSwapSector: + case *rhp3.InstrSwapSector: return "SwapSector" - case *rhpv3.InstrUpdateSector: + case *rhp3.InstrUpdateSector: return "UpdateSector" - case *rhpv3.InstrStoreSector: + case *rhp3.InstrStoreSector: return "StoreSector" - case *rhpv3.InstrRevision: + case *rhp3.InstrRevision: return "Revision" - case *rhpv3.InstrReadRegistry, *rhpv3.InstrReadRegistryNoVersion: + case *rhp3.InstrReadRegistry, *rhp3.InstrReadRegistryNoVersion: return "ReadRegistry" - case *rhpv3.InstrUpdateRegistry, *rhpv3.InstrUpdateRegistryNoType: + case *rhp3.InstrUpdateRegistry, *rhp3.InstrUpdateRegistryNoType: return "UpdateRegistry" default: panic(fmt.Sprintf("unknown instruction type %T", instr)) } } -func costToAccountUsage(cost rhpv3.ResourceCost) accounts.Usage { +func costToAccountUsage(cost rhp3.ResourceCost) accounts.Usage { return accounts.Usage{ RPCRevenue: cost.Base, StorageRevenue: cost.Storage, diff --git a/rhp/v3/execute_test.go b/rhp/v3/execute_test.go index fd74430e..3845aae8 100644 --- a/rhp/v3/execute_test.go +++ b/rhp/v3/execute_test.go @@ -3,19 +3,19 @@ package rhp import ( "testing" - rhpv2 "go.sia.tech/core/rhp/v2" + rhp2 "go.sia.tech/core/rhp/v2" "lukechampine.com/frand" ) func BenchmarkReadSector(b *testing.B) { - data := programData(frand.Bytes((rhpv2.SectorSize) * 4)) + data := programData(frand.Bytes((rhp2.SectorSize) * 4)) - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - _, _, err := data.Sector(0) + _, err := data.Sector(0) if err != nil { b.Fatal(err) } diff --git a/rhp/v3/payments.go b/rhp/v3/payments.go index ab9cedd3..f575a548 100644 --- a/rhp/v3/payments.go +++ b/rhp/v3/payments.go @@ -6,7 +6,7 @@ import ( "fmt" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/accounts" "go.sia.tech/hostd/host/contracts" @@ -14,10 +14,10 @@ import ( ) // processContractPayment initializes an RPC budget using funds from a contract. -func (sh *SessionHandler) processContractPayment(s *rhpv3.Stream, height uint64) (rhpv3.Account, types.Currency, error) { - var req rhpv3.PayByContractRequest +func (sh *SessionHandler) processContractPayment(s *rhp3.Stream, height uint64) (rhp3.Account, types.Currency, error) { + var req rhp3.PayByContractRequest if err := s.ReadRequest(&req, maxRequestSize); err != nil { - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to read contract payment request: %w", err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to read contract payment request: %w", err) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) @@ -26,7 +26,7 @@ func (sh *SessionHandler) processContractPayment(s *rhpv3.Stream, height uint64) contract, err := sh.contracts.Lock(ctx, req.ContractID) if err != nil { s.WriteResponseErr(ErrHostInternalError) - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to lock contract %v: %w", req.ContractID, err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to lock contract %v: %w", req.ContractID, err) } defer sh.contracts.Unlock(req.ContractID) @@ -35,7 +35,7 @@ func (sh *SessionHandler) processContractPayment(s *rhpv3.Stream, height uint64) if err != nil { err = fmt.Errorf("failed to revise contract: %w", err) s.WriteResponseErr(err) - return rhpv3.ZeroAccount, types.ZeroCurrency, err + return rhp3.ZeroAccount, types.ZeroCurrency, err } // calculate the funding amount @@ -43,26 +43,26 @@ func (sh *SessionHandler) processContractPayment(s *rhpv3.Stream, height uint64) if underflow { err = errors.New("invalid payment revision: new revision has more funds than current revision") s.WriteResponseErr(err) - return rhpv3.ZeroAccount, types.ZeroCurrency, err + return rhp3.ZeroAccount, types.ZeroCurrency, err } // validate that new revision if err := rhp.ValidatePaymentRevision(current, revision, fundAmount); err != nil { err = fmt.Errorf("invalid payment revision: %w", err) s.WriteResponseErr(err) - return rhpv3.ZeroAccount, types.ZeroCurrency, err + return rhp3.ZeroAccount, types.ZeroCurrency, err } // verify the renter's signature sigHash := rhp.HashRevision(revision) if !contract.RenterKey().VerifyHash(sigHash, req.Signature) { - return rhpv3.ZeroAccount, types.ZeroCurrency, ErrInvalidRenterSignature + return rhp3.ZeroAccount, types.ZeroCurrency, ErrInvalidRenterSignature } settings := sh.settings.Settings() if err != nil { s.WriteResponseErr(ErrHostInternalError) - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to get host settings: %w", err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to get host settings: %w", err) } hostSig := sh.privateKey.SignHash(sigHash) @@ -84,60 +84,60 @@ func (sh *SessionHandler) processContractPayment(s *rhpv3.Stream, height uint64) } else { s.WriteResponseErr(ErrHostInternalError) } - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to credit refund account: %w", err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to credit refund account: %w", err) } // send the updated host signature to the renter - err = s.WriteResponse(&rhpv3.PaymentResponse{ + err = s.WriteResponse(&rhp3.PaymentResponse{ Signature: hostSig, }) if err != nil { - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to send host signature response: %w", err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to send host signature response: %w", err) } return req.RefundAccount, fundAmount, nil } // processAccountPayment initializes an RPC budget using an ephemeral // account. -func (sh *SessionHandler) processAccountPayment(s *rhpv3.Stream, height uint64) (rhpv3.Account, types.Currency, error) { - var req rhpv3.PayByEphemeralAccountRequest +func (sh *SessionHandler) processAccountPayment(s *rhp3.Stream, height uint64) (rhp3.Account, types.Currency, error) { + var req rhp3.PayByEphemeralAccountRequest if err := s.ReadRequest(&req, maxRequestSize); err != nil { - return rhpv3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to read ephemeral account payment request: %w", err) + return rhp3.ZeroAccount, types.ZeroCurrency, fmt.Errorf("failed to read ephemeral account payment request: %w", err) } switch { case req.Expiry < height: - return rhpv3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request expired") + return rhp3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request expired") case req.Expiry > height+20: - return rhpv3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request too far in the future") + return rhp3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request too far in the future") case req.Amount.IsZero(): - return rhpv3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request has zero amount") - case req.Account == rhpv3.ZeroAccount: - return rhpv3.ZeroAccount, types.ZeroCurrency, errors.New("cannot withdraw from zero account") + return rhp3.ZeroAccount, types.ZeroCurrency, errors.New("withdrawal request has zero amount") + case req.Account == rhp3.ZeroAccount: + return rhp3.ZeroAccount, types.ZeroCurrency, errors.New("cannot withdraw from zero account") case !types.PublicKey(req.Account).VerifyHash(req.SigHash(), req.Signature): - return rhpv3.ZeroAccount, types.ZeroCurrency, ErrInvalidRenterSignature + return rhp3.ZeroAccount, types.ZeroCurrency, ErrInvalidRenterSignature } return req.Account, req.Amount, nil } // processPayment initializes an RPC budget using funds from a contract or an // ephemeral account. -func (sh *SessionHandler) processPayment(s *rhpv3.Stream, pt *rhpv3.HostPriceTable) (*accounts.Budget, error) { +func (sh *SessionHandler) processPayment(s *rhp3.Stream, pt *rhp3.HostPriceTable) (*accounts.Budget, error) { var paymentType types.Specifier if err := s.ReadRequest(&paymentType, 16); err != nil { return nil, fmt.Errorf("failed to read payment type: %w", err) } - var account rhpv3.Account + var account rhp3.Account var amount types.Currency var err error currentHeight := pt.HostBlockHeight switch paymentType { - case rhpv3.PaymentTypeContract: + case rhp3.PaymentTypeContract: account, amount, err = sh.processContractPayment(s, currentHeight) if err != nil { return nil, fmt.Errorf("failed to process contract payment: %w", err) } - case rhpv3.PaymentTypeEphemeralAccount: + case rhp3.PaymentTypeEphemeralAccount: account, amount, err = sh.processAccountPayment(s, currentHeight) if err != nil { return nil, fmt.Errorf("failed to process account payment: %w", err) @@ -153,14 +153,14 @@ func (sh *SessionHandler) processPayment(s *rhpv3.Stream, pt *rhpv3.HostPriceTab // processFundAccountPayment processes a contract payment to fund an account for // RPCFundAccount returning the fund amount and the current balance of the // account. Accounts can only be funded by a contract. -func (sh *SessionHandler) processFundAccountPayment(pt rhpv3.HostPriceTable, s *rhpv3.Stream, accountID rhpv3.Account) (fundAmount, balance types.Currency, _ error) { +func (sh *SessionHandler) processFundAccountPayment(pt rhp3.HostPriceTable, s *rhp3.Stream, accountID rhp3.Account) (fundAmount, balance types.Currency, _ error) { var paymentType types.Specifier if err := s.ReadRequest(&paymentType, 16); err != nil { return types.ZeroCurrency, types.ZeroCurrency, fmt.Errorf("failed to read payment type: %w", err) - } else if paymentType != rhpv3.PaymentTypeContract { + } else if paymentType != rhp3.PaymentTypeContract { return types.ZeroCurrency, types.ZeroCurrency, fmt.Errorf("unrecognized payment type: %q", paymentType) } - var req rhpv3.PayByContractRequest + var req rhp3.PayByContractRequest if err := s.ReadRequest(&req, maxRequestSize); err != nil { return types.ZeroCurrency, types.ZeroCurrency, fmt.Errorf("failed to read contract payment request: %w", err) } @@ -235,7 +235,7 @@ func (sh *SessionHandler) processFundAccountPayment(pt rhpv3.HostPriceTable, s * } // send the updated host signature to the renter - err = s.WriteResponse(&rhpv3.PaymentResponse{ + err = s.WriteResponse(&rhp3.PaymentResponse{ Signature: hostSig, }) if err != nil { diff --git a/rhp/v3/pricetable.go b/rhp/v3/pricetable.go index e60e961c..96e3b028 100644 --- a/rhp/v3/pricetable.go +++ b/rhp/v3/pricetable.go @@ -7,7 +7,7 @@ import ( "sync" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "lukechampine.com/frand" ) @@ -15,7 +15,7 @@ import ( type ( // expiringPriceTable pairs a price table UID with an expiration timestamp. expiringPriceTable struct { - uid rhpv3.SettingsID + uid rhp3.SettingsID expiry time.Time } @@ -33,7 +33,7 @@ type ( expirationTimer *time.Timer // priceTables is a map of valid price tables. The key is the UID of the // price table. Keys are removed by the loop in pruneExpired. - priceTables map[rhpv3.SettingsID]rhpv3.HostPriceTable + priceTables map[rhp3.SettingsID]rhp3.HostPriceTable } ) @@ -71,18 +71,18 @@ func (pm *priceTableManager) pruneExpired() { // Get returns the price table with the given UID if it exists and // has not expired. -func (pm *priceTableManager) Get(id [16]byte) (rhpv3.HostPriceTable, error) { +func (pm *priceTableManager) Get(id [16]byte) (rhp3.HostPriceTable, error) { pm.mu.RLock() pt, ok := pm.priceTables[id] pm.mu.RUnlock() if !ok { - return rhpv3.HostPriceTable{}, ErrNoPriceTable + return rhp3.HostPriceTable{}, ErrNoPriceTable } return pt, nil } // Register adds a price table to the list of valid price tables. -func (pm *priceTableManager) Register(pt rhpv3.HostPriceTable) { +func (pm *priceTableManager) Register(pt rhp3.HostPriceTable) { pm.mu.Lock() defer pm.mu.Unlock() @@ -105,17 +105,17 @@ func (pm *priceTableManager) Register(pt rhpv3.HostPriceTable) { } // PriceTable returns the session handler's current price table. -func (sh *SessionHandler) PriceTable() (rhpv3.HostPriceTable, error) { +func (sh *SessionHandler) PriceTable() (rhp3.HostPriceTable, error) { settings := sh.settings.Settings() count, max, err := sh.registry.Entries() if err != nil { - return rhpv3.HostPriceTable{}, fmt.Errorf("failed to get registry entries: %w", err) + return rhp3.HostPriceTable{}, fmt.Errorf("failed to get registry entries: %w", err) } fee := sh.tpool.RecommendedFee() currentHeight := sh.chain.TipState().Index.Height oneHasting := types.NewCurrency64(1) - return rhpv3.HostPriceTable{ + return rhp3.HostPriceTable{ UID: frand.Entropy128(), HostBlockHeight: currentHeight, Validity: settings.PriceTableValidity, @@ -173,11 +173,11 @@ func (sh *SessionHandler) PriceTable() (rhpv3.HostPriceTable, error) { // readPriceTable reads the price table ID from the stream and returns an error // if the price table is invalid or expired. -func (sh *SessionHandler) readPriceTable(s *rhpv3.Stream) (rhpv3.HostPriceTable, error) { +func (sh *SessionHandler) readPriceTable(s *rhp3.Stream) (rhp3.HostPriceTable, error) { // read the price table ID from the stream - var uid rhpv3.SettingsID + var uid rhp3.SettingsID if err := s.ReadRequest(&uid, 16); err != nil { - return rhpv3.HostPriceTable{}, fmt.Errorf("failed to read price table ID: %w", err) + return rhp3.HostPriceTable{}, fmt.Errorf("failed to read price table ID: %w", err) } return sh.priceTables.Get(uid) } @@ -187,7 +187,7 @@ func (sh *SessionHandler) readPriceTable(s *rhpv3.Stream) (rhpv3.HostPriceTable, func newPriceTableManager() *priceTableManager { pm := &priceTableManager{ expirationList: list.New(), - priceTables: make(map[rhpv3.SettingsID]rhpv3.HostPriceTable), + priceTables: make(map[rhp3.SettingsID]rhp3.HostPriceTable), } return pm } diff --git a/rhp/v3/pricetable_test.go b/rhp/v3/pricetable_test.go index de0a83cd..62b077b2 100644 --- a/rhp/v3/pricetable_test.go +++ b/rhp/v3/pricetable_test.go @@ -5,14 +5,14 @@ import ( "testing" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "lukechampine.com/frand" ) func TestPriceTableManager(t *testing.T) { pm := newPriceTableManager() t.Run("serial", func(t *testing.T) { - pt := rhpv3.HostPriceTable{ + pt := rhp3.HostPriceTable{ UID: frand.Entropy128(), Validity: 100 * time.Millisecond, } @@ -51,7 +51,7 @@ func TestPriceTableManager(t *testing.T) { wg.Add(len(tables)) for _, id := range tables { go func(id [16]byte) { - pm.Register(rhpv3.HostPriceTable{ + pm.Register(rhp3.HostPriceTable{ UID: id, Validity: 250 * time.Millisecond, }) diff --git a/rhp/v3/rhp.go b/rhp/v3/rhp.go index bae35a6b..8bf80092 100644 --- a/rhp/v3/rhp.go +++ b/rhp/v3/rhp.go @@ -8,8 +8,8 @@ import ( "time" "go.sia.tech/core/consensus" - rhpv2 "go.sia.tech/core/rhp/v2" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp2 "go.sia.tech/core/rhp/v2" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/accounts" "go.sia.tech/hostd/host/contracts" @@ -24,9 +24,9 @@ import ( type ( // An AccountManager manages deposits and withdrawals for accounts. AccountManager interface { - Balance(accountID rhpv3.Account) (types.Currency, error) + Balance(accountID rhp3.Account) (types.Currency, error) Credit(req accounts.FundAccountWithContract, refund bool) (balance types.Currency, err error) - Budget(accountID rhpv3.Account, amount types.Currency) (*accounts.Budget, error) + Budget(accountID rhp3.Account, amount types.Currency) (*accounts.Budget, error) } // A ContractManager manages the set of contracts that the host is currently @@ -64,9 +64,9 @@ type ( // Write writes a sector to persistent storage. release should only be // called after the contract roots have been committed to prevent the // sector from being deleted. - Write(root types.Hash256, data *[rhpv2.SectorSize]byte) (release func() error, _ error) + Write(root types.Hash256, data *[rhp2.SectorSize]byte) (release func() error, _ error) // Read reads the sector with the given root from the manager. - Read(root types.Hash256) (*[rhpv2.SectorSize]byte, error) + Read(root types.Hash256) (*[rhp2.SectorSize]byte, error) // Sync syncs the data files of changed volumes. Sync() error @@ -78,8 +78,8 @@ type ( // A RegistryManager manages registry entries stored in a RegistryStore. RegistryManager interface { - Get(key rhpv3.RegistryKey) (rhpv3.RegistryValue, error) - Put(value rhpv3.RegistryEntry, expirationHeight uint64) (rhpv3.RegistryValue, error) + Get(key rhp3.RegistryKey) (rhp3.RegistryValue, error) + Put(value rhp3.RegistryEntry, expirationHeight uint64) (rhp3.RegistryValue, error) Entries() (count uint64, max uint64, err error) } @@ -171,7 +171,7 @@ var ( ) // handleHostStream handles streams routed to the "host" subscriber -func (sh *SessionHandler) handleHostStream(s *rhpv3.Stream, sessionID rhp.UID, log *zap.Logger) { +func (sh *SessionHandler) handleHostStream(s *rhp3.Stream, sessionID rhp.UID, log *zap.Logger) { defer s.Close() // close the stream when the RPC has completed done, err := sh.tg.Add() // add the RPC to the threadgroup @@ -186,13 +186,13 @@ func (sh *SessionHandler) handleHostStream(s *rhpv3.Stream, sessionID rhp.UID, l log.Debug("failed to read RPC ID", zap.Error(err)) return } - rpcs := map[types.Specifier]func(*rhpv3.Stream, *zap.Logger) (contracts.Usage, error){ - rhpv3.RPCAccountBalanceID: sh.handleRPCAccountBalance, - rhpv3.RPCUpdatePriceTableID: sh.handleRPCPriceTable, - rhpv3.RPCExecuteProgramID: sh.handleRPCExecute, - rhpv3.RPCFundAccountID: sh.handleRPCFundAccount, - rhpv3.RPCLatestRevisionID: sh.handleRPCLatestRevision, - rhpv3.RPCRenewContractID: sh.handleRPCRenew, + rpcs := map[types.Specifier]func(*rhp3.Stream, *zap.Logger) (contracts.Usage, error){ + rhp3.RPCAccountBalanceID: sh.handleRPCAccountBalance, + rhp3.RPCUpdatePriceTableID: sh.handleRPCPriceTable, + rhp3.RPCExecuteProgramID: sh.handleRPCExecute, + rhp3.RPCFundAccountID: sh.handleRPCFundAccount, + rhp3.RPCLatestRevisionID: sh.handleRPCLatestRevision, + rhp3.RPCRenewContractID: sh.handleRPCRenew, } rpcFn, ok := rpcs[rpc] if !ok { @@ -250,7 +250,7 @@ func (sh *SessionHandler) Serve() error { log := sh.log.With(zap.Stringer("sessionID", sessionID), zap.String("peerAddress", conn.RemoteAddr().String())) // upgrade the connection to RHP3 - t, err := rhpv3.NewHostTransport(rhpConn, sh.privateKey) + t, err := rhp3.NewHostTransport(rhpConn, sh.privateKey) if err != nil { log.Debug("failed to upgrade conn", zap.Error(err)) return diff --git a/rhp/v3/rpc.go b/rhp/v3/rpc.go index 1ac8aa85..33941b8a 100644 --- a/rhp/v3/rpc.go +++ b/rhp/v3/rpc.go @@ -10,7 +10,7 @@ import ( "strings" "time" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/accounts" "go.sia.tech/hostd/host/contracts" @@ -43,7 +43,7 @@ var ( ) // handleRPCPriceTable sends the host's price table to the renter. -func (sh *SessionHandler) handleRPCPriceTable(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCPriceTable(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { pt, err := sh.PriceTable() if err != nil { s.WriteResponseErr(ErrHostInternalError) @@ -55,7 +55,7 @@ func (sh *SessionHandler) handleRPCPriceTable(s *rhpv3.Stream, log *zap.Logger) return contracts.Usage{}, fmt.Errorf("failed to marshal price table: %w", err) } - resp := &rhpv3.RPCUpdatePriceTableResponse{ + resp := &rhp3.RPCUpdatePriceTableResponse{ PriceTableJSON: buf, } if err := s.WriteResponse(resp); err != nil { @@ -87,10 +87,10 @@ func (sh *SessionHandler) handleRPCPriceTable(s *rhpv3.Stream, log *zap.Logger) usage := contracts.Usage{ RPCRevenue: pt.UpdatePriceTableCost, } - return usage, s.WriteResponse(&rhpv3.RPCPriceTableResponse{}) + return usage, s.WriteResponse(&rhp3.RPCPriceTableResponse{}) } -func (sh *SessionHandler) handleRPCFundAccount(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCFundAccount(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { s.SetDeadline(time.Now().Add(time.Minute)) // read the price table ID from the stream pt, err := sh.readPriceTable(s) @@ -101,7 +101,7 @@ func (sh *SessionHandler) handleRPCFundAccount(s *rhpv3.Stream, log *zap.Logger) } // read the fund request from the stream - var fundReq rhpv3.RPCFundAccountRequest + var fundReq rhp3.RPCFundAccountRequest if err := s.ReadRequest(&fundReq, 32); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read fund account request: %w", err) } @@ -114,9 +114,9 @@ func (sh *SessionHandler) handleRPCFundAccount(s *rhpv3.Stream, log *zap.Logger) return contracts.Usage{}, err } - fundResp := &rhpv3.RPCFundAccountResponse{ + fundResp := &rhp3.RPCFundAccountResponse{ Balance: balance, - Receipt: rhpv3.FundAccountReceipt{ + Receipt: rhp3.FundAccountReceipt{ Host: sh.HostKey(), Account: fundReq.Account, Amount: fundAmount, @@ -134,7 +134,7 @@ func (sh *SessionHandler) handleRPCFundAccount(s *rhpv3.Stream, log *zap.Logger) return usage, s.WriteResponse(fundResp) } -func (sh *SessionHandler) handleRPCAccountBalance(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCAccountBalance(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { s.SetDeadline(time.Now().Add(time.Minute)) // get the price table to use for payment pt, err := sh.readPriceTable(s) @@ -161,7 +161,7 @@ func (sh *SessionHandler) handleRPCAccountBalance(s *rhpv3.Stream, log *zap.Logg } // read the account balance request from the stream - var req rhpv3.RPCAccountBalanceRequest + var req rhp3.RPCAccountBalanceRequest if err := s.ReadRequest(&req, 32); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read account balance request: %w", err) } @@ -173,7 +173,7 @@ func (sh *SessionHandler) handleRPCAccountBalance(s *rhpv3.Stream, log *zap.Logg return contracts.Usage{}, fmt.Errorf("failed to get account balance: %w", err) } - resp := &rhpv3.RPCAccountBalanceResponse{ + resp := &rhp3.RPCAccountBalanceResponse{ Balance: balance, } if err := budget.Commit(); err != nil { @@ -185,9 +185,9 @@ func (sh *SessionHandler) handleRPCAccountBalance(s *rhpv3.Stream, log *zap.Logg return usage, s.WriteResponse(resp) } -func (sh *SessionHandler) handleRPCLatestRevision(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCLatestRevision(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { s.SetDeadline(time.Now().Add(time.Minute)) - var req rhpv3.RPCLatestRevisionRequest + var req rhp3.RPCLatestRevisionRequest if err := s.ReadRequest(&req, maxRequestSize); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read latest revision request: %w", err) } @@ -199,7 +199,7 @@ func (sh *SessionHandler) handleRPCLatestRevision(s *rhpv3.Stream, log *zap.Logg return contracts.Usage{}, err } - resp := &rhpv3.RPCLatestRevisionResponse{ + resp := &rhp3.RPCLatestRevisionResponse{ Revision: contract.Revision, } if err := s.WriteResponse(resp); err != nil { @@ -238,7 +238,7 @@ func (sh *SessionHandler) handleRPCLatestRevision(s *rhpv3.Stream, log *zap.Logg return usage, nil } -func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCRenew(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { s.SetDeadline(time.Now().Add(2 * time.Minute)) if !sh.settings.Settings().AcceptingContracts { s.WriteResponseErr(ErrNotAcceptingContracts) @@ -257,7 +257,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont s.WriteResponseErr(ErrHostInternalError) return contracts.Usage{}, fmt.Errorf("failed to marshal price table: %w", err) } - ptResp := &rhpv3.RPCUpdatePriceTableResponse{ + ptResp := &rhp3.RPCUpdatePriceTableResponse{ PriceTableJSON: buf, } if err := s.WriteResponse(ptResp); err != nil { @@ -267,7 +267,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont return contracts.Usage{}, fmt.Errorf("failed to read price table: %w", err) } - var req rhpv3.RPCRenewContractRequest + var req rhp3.RPCRenewContractRequest if err := s.ReadRequest(&req, 10*maxRequestSize); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renew contract request: %w", err) } else if err := validRenewalTxnSet(req.TransactionSet); err != nil { @@ -344,7 +344,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont } defer release() - hostAdditions := &rhpv3.RPCRenewContractHostAdditions{ + hostAdditions := &rhp3.RPCRenewContractHostAdditions{ SiacoinInputs: renewalTxn.SiacoinInputs[renterInputs:], SiacoinOutputs: renewalTxn.SiacoinOutputs[renterOutputs:], FinalRevisionSignature: signedClearingRevision.HostSignature, @@ -353,7 +353,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont return contracts.Usage{}, fmt.Errorf("failed to write host additions: %w", err) } - var renterSigsResp rhpv3.RPCRenewSignatures + var renterSigsResp rhp3.RPCRenewSignatures if err := s.ReadRequest(&renterSigsResp, 10*maxRequestSize); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read renter signatures: %w", err) } @@ -423,7 +423,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont } // send the signatures to the renter - hostSigs := &rhpv3.RPCRenewSignatures{ + hostSigs := &rhp3.RPCRenewSignatures{ TransactionSignatures: renewalTxn.Signatures[renterSigs:], RevisionSignature: types.TransactionSignature{ ParentID: types.Hash256(signedRenewal.Revision.ParentID), @@ -438,7 +438,7 @@ func (sh *SessionHandler) handleRPCRenew(s *rhpv3.Stream, log *zap.Logger) (cont } // handleRPCExecute handles an RPCExecuteProgram request. -func (sh *SessionHandler) handleRPCExecute(s *rhpv3.Stream, log *zap.Logger) (contracts.Usage, error) { +func (sh *SessionHandler) handleRPCExecute(s *rhp3.Stream, log *zap.Logger) (contracts.Usage, error) { s.SetDeadline(time.Now().Add(5 * time.Minute)) // read the price table pt, err := sh.readPriceTable(s) @@ -460,7 +460,7 @@ func (sh *SessionHandler) handleRPCExecute(s *rhpv3.Stream, log *zap.Logger) (co // read the program request readReqStart := time.Now() - var executeReq rhpv3.RPCExecuteProgramRequest + var executeReq rhp3.RPCExecuteProgramRequest if err := s.ReadRequest(&executeReq, maxProgramRequestSize); err != nil { return contracts.Usage{}, fmt.Errorf("failed to read execute request: %w", err) } diff --git a/rhp/v3/rpc_test.go b/rhp/v3/rpc_test.go index dfc0e932..03c63489 100644 --- a/rhp/v3/rpc_test.go +++ b/rhp/v3/rpc_test.go @@ -8,8 +8,8 @@ import ( "testing" "time" - rhpv2 "go.sia.tech/core/rhp/v2" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp2 "go.sia.tech/core/rhp/v2" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/core/types" "go.sia.tech/hostd/host/settings" "go.sia.tech/hostd/internal/test" @@ -27,12 +27,12 @@ func TestPriceTable(t *testing.T) { defer renter.Close() defer host.Close() - pt, err := host.RHPv3PriceTable() + pt, err := host.RHP3PriceTable() if err != nil { t.Fatal(err) } - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } @@ -49,12 +49,12 @@ func TestPriceTable(t *testing.T) { } // pay for a price table using a contract payment - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), 200) if err != nil { t.Fatal(err) } - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) retrieved, err = session.RegisterPriceTable(payment) @@ -95,19 +95,19 @@ func TestAppendSector(t *testing.T) { defer renter.Close() defer host.Close() - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } defer session.Close() - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) if err != nil { t.Fatal(err) } // register the price table - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) pt, err := session.RegisterPriceTable(payment) if err != nil { @@ -127,9 +127,9 @@ func TestAppendSector(t *testing.T) { if cost.IsZero() { t.Fatal("cost is zero") } - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) roots = append(roots, root) if _, err = session.AppendSector(§or, &revision, renter.PrivateKey(), payment, cost); err != nil { @@ -137,13 +137,13 @@ func TestAppendSector(t *testing.T) { } // check that the contract merkle root matches - if revision.Revision.FileMerkleRoot != rhpv2.MetaRoot(roots) { + if revision.Revision.FileMerkleRoot != rhp2.MetaRoot(roots) { t.Fatal("contract merkle root doesn't match") } // download the sector - cost, _ = pt.BaseCost().Add(pt.ReadSectorCost(rhpv2.SectorSize)).Total() - downloaded, _, err := session.ReadSector(root, 0, rhpv2.SectorSize, payment, cost) + cost, _ = pt.BaseCost().Add(pt.ReadSectorCost(rhp2.SectorSize)).Total() + downloaded, _, err := session.ReadSector(root, 0, rhp2.SectorSize, payment, cost) if err != nil { t.Fatal(err) } else if !bytes.Equal(downloaded, sector[:]) { @@ -164,18 +164,18 @@ func TestStoreSector(t *testing.T) { // Resize cache to 0 sectors host.Storage().ResizeCache(0) - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } defer session.Close() - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) if err != nil { t.Fatal(err) } - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) // register the price table payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) pt, err := session.RegisterPriceTable(payment) @@ -194,17 +194,17 @@ func TestStoreSector(t *testing.T) { // calculate the cost of the upload usage := pt.StoreSectorCost(10) cost, _ := usage.Total() - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) - root := rhpv2.SectorRoot(§or) + root := rhp2.SectorRoot(§or) if err = session.StoreSector(§or, 10, payment, cost); err != nil { t.Fatal(err) } // download the sector - usage = pt.ReadSectorCost(rhpv2.SectorSize) + usage = pt.ReadSectorCost(rhp2.SectorSize) cost, _ = usage.Total() - downloaded, _, err := session.ReadSector(root, 0, rhpv2.SectorSize, payment, cost) + downloaded, _, err := session.ReadSector(root, 0, rhp2.SectorSize, payment, cost) if err != nil { t.Fatal(err) } else if !bytes.Equal(downloaded, sector[:]) { @@ -218,9 +218,9 @@ func TestStoreSector(t *testing.T) { time.Sleep(100 * time.Millisecond) // sync time // check that the sector was deleted - usage = pt.ReadSectorCost(rhpv2.SectorSize) + usage = pt.ReadSectorCost(rhp2.SectorSize) cost, _ = usage.Total() - _, _, err = session.ReadSector(root, 0, rhpv2.SectorSize, payment, cost) + _, _, err = session.ReadSector(root, 0, rhp2.SectorSize, payment, cost) if err == nil { t.Fatal("expected error when reading sector") } @@ -235,18 +235,18 @@ func TestReadSectorOffset(t *testing.T) { defer renter.Close() defer host.Close() - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } defer session.Close() - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(100), types.Siacoins(200), 200) if err != nil { t.Fatal(err) } - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) // register the price table pt, err := session.RegisterPriceTable(payment) @@ -261,7 +261,7 @@ func TestReadSectorOffset(t *testing.T) { } cost, _ := pt.BaseCost().Add(pt.AppendSectorCost(revision.Revision.WindowEnd - renter.TipState().Index.Height)).Total() - var sectors [][rhpv2.SectorSize]byte + var sectors [][rhp2.SectorSize]byte for i := 0; i < 5; i++ { // upload a few sectors payment = proto3.AccountPayment(account, renter.PrivateKey()) @@ -269,7 +269,7 @@ func TestReadSectorOffset(t *testing.T) { if cost.IsZero() { t.Fatal("cost is zero") } - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) _, err = session.AppendSector(§or, &revision, renter.PrivateKey(), payment, cost) if err != nil { @@ -280,7 +280,7 @@ func TestReadSectorOffset(t *testing.T) { // download the sector cost, _ = pt.BaseCost().Add(pt.ReadOffsetCost(256)).Total() - downloaded, _, err := session.ReadOffset(rhpv2.SectorSize*3+64, 256, revision.ID(), payment, cost) + downloaded, _, err := session.ReadOffset(rhp2.SectorSize*3+64, 256, revision.ID(), payment, cost) if err != nil { t.Fatal(err) } else if !bytes.Equal(downloaded, sectors[3][64:64+256]) { @@ -300,12 +300,12 @@ func TestRenew(t *testing.T) { t.Run("empty contract", func(t *testing.T) { state := renter.TipState() // form a contract - origin, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) + origin, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) if err != nil { t.Fatal(err) } - settings, err := renter.Settings(context.Background(), host.RHPv2Addr(), host.PublicKey()) + settings, err := renter.Settings(context.Background(), host.RHP2Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } @@ -316,13 +316,13 @@ func TestRenew(t *testing.T) { } time.Sleep(100 * time.Millisecond) - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } defer session.Close() - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) payment := proto3.ContractPayment(&origin, renter.PrivateKey(), account) // register a price table to use for the renewal pt, err := session.RegisterPriceTable(payment) @@ -382,23 +382,23 @@ func TestRenew(t *testing.T) { t.Run("non-empty contract", func(t *testing.T) { // form a contract state := renter.TipState() - origin, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) + origin, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(10), types.Siacoins(20), state.Index.Height+200) if err != nil { t.Fatal(err) } - settings, err := renter.Settings(context.Background(), host.RHPv2Addr(), host.PublicKey()) + settings, err := renter.Settings(context.Background(), host.RHP2Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { t.Fatal(err) } defer session.Close() - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) payment := proto3.ContractPayment(&origin, renter.PrivateKey(), account) // register a price table to use for the renewal pt, err := session.RegisterPriceTable(payment) @@ -412,7 +412,7 @@ func TestRenew(t *testing.T) { } // generate a sector - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) // calculate the remaining duration of the contract @@ -496,18 +496,18 @@ func BenchmarkAppendSector(b *testing.B) { defer renter.Close() defer host.Close() - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { b.Fatal(err) } defer session.Close() - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(50), types.Siacoins(100), 200) if err != nil { b.Fatal(err) } - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) // register the price table payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) pt, err := session.RegisterPriceTable(payment) @@ -528,16 +528,16 @@ func BenchmarkAppendSector(b *testing.B) { b.Fatal("cost is zero") } - var sectors [][rhpv2.SectorSize]byte + var sectors [][rhp2.SectorSize]byte for i := 0; i < b.N; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) sectors = append(sectors, sector) } b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) for i := 0; i < b.N; i++ { _, err = session.AppendSector(§ors[i], &revision, renter.PrivateKey(), payment, cost) @@ -570,18 +570,18 @@ func BenchmarkReadSector(b *testing.B) { b.Fatal(err) } - session, err := renter.NewRHP3Session(context.Background(), host.RHPv3Addr(), host.PublicKey()) + session, err := renter.NewRHP3Session(context.Background(), host.RHP3Addr(), host.PublicKey()) if err != nil { b.Fatal(err) } defer session.Close() - revision, err := renter.FormContract(context.Background(), host.RHPv2Addr(), host.PublicKey(), types.Siacoins(500), types.Siacoins(1000), 200) + revision, err := renter.FormContract(context.Background(), host.RHP2Addr(), host.PublicKey(), types.Siacoins(500), types.Siacoins(1000), 200) if err != nil { b.Fatal(err) } - account := rhpv3.Account(renter.PublicKey()) + account := rhp3.Account(renter.PublicKey()) // register the price table payment := proto3.ContractPayment(&revision, renter.PrivateKey(), account) pt, err := session.RegisterPriceTable(payment) @@ -605,22 +605,22 @@ func BenchmarkReadSector(b *testing.B) { var roots []types.Hash256 for i := 0; i < b.N; i++ { - var sector [rhpv2.SectorSize]byte + var sector [rhp2.SectorSize]byte frand.Read(sector[:256]) _, err = session.AppendSector(§or, &revision, renter.PrivateKey(), payment, cost) if err != nil { b.Fatal(err) } - roots = append(roots, rhpv2.SectorRoot(§or)) + roots = append(roots, rhp2.SectorRoot(§or)) } b.ResetTimer() b.ReportAllocs() - b.SetBytes(rhpv2.SectorSize) + b.SetBytes(rhp2.SectorSize) for i := 0; i < b.N; i++ { - _, _, err = session.ReadSector(roots[i], 0, rhpv2.SectorSize, payment, cost) + _, _, err = session.ReadSector(roots[i], 0, rhp2.SectorSize, payment, cost) if err != nil { b.Fatal(err) } diff --git a/rhp/v3/websocket_test.go b/rhp/v3/websocket_test.go index 44efaeb1..ea212198 100644 --- a/rhp/v3/websocket_test.go +++ b/rhp/v3/websocket_test.go @@ -5,7 +5,7 @@ import ( "encoding/json" "testing" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/hostd/internal/test" "go.uber.org/zap/zaptest" "nhooyr.io/websocket" @@ -20,14 +20,14 @@ func TestWebSockets(t *testing.T) { defer renter.Close() defer host.Close() - c, _, err := websocket.Dial(context.Background(), "ws://"+host.RHPv3WSAddr()+"/ws", nil) + c, _, err := websocket.Dial(context.Background(), "ws://"+host.RHP3WSAddr()+"/ws", nil) if err != nil { t.Fatal(err) } defer c.Close(websocket.StatusNormalClosure, "") conn := websocket.NetConn(context.Background(), c, websocket.MessageBinary) - transport, err := rhpv3.NewRenterTransport(conn, host.PublicKey()) + transport, err := rhp3.NewRenterTransport(conn, host.PublicKey()) if err != nil { t.Fatal(err) } @@ -36,14 +36,14 @@ func TestWebSockets(t *testing.T) { stream := transport.DialStream() defer stream.Close() - if err := stream.WriteRequest(rhpv3.RPCUpdatePriceTableID, nil); err != nil { + if err := stream.WriteRequest(rhp3.RPCUpdatePriceTableID, nil); err != nil { t.Fatal(err) } - var resp rhpv3.RPCUpdatePriceTableResponse + var resp rhp3.RPCUpdatePriceTableResponse if err := stream.ReadResponse(&resp, 4096); err != nil { t.Fatal(err) } - var pt rhpv3.HostPriceTable + var pt rhp3.HostPriceTable if err := json.Unmarshal(resp.PriceTableJSON, &pt); err != nil { t.Fatal(err) } diff --git a/rhp/v3/websockets.go b/rhp/v3/websockets.go index 87f8ec5c..9ea4dbe8 100644 --- a/rhp/v3/websockets.go +++ b/rhp/v3/websockets.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - rhpv3 "go.sia.tech/core/rhp/v3" + rhp3 "go.sia.tech/core/rhp/v3" "go.sia.tech/hostd/rhp" "go.uber.org/zap" "nhooyr.io/websocket" @@ -38,7 +38,7 @@ func (sh *SessionHandler) handleWebSockets(w http.ResponseWriter, r *http.Reques log = log.With(zap.String("sessionID", sessionID.String())) // upgrade the connection - t, err := rhpv3.NewHostTransport(rhpConn, sh.privateKey) + t, err := rhp3.NewHostTransport(rhpConn, sh.privateKey) if err != nil { sh.log.Debug("failed to upgrade conn", zap.Error(err), zap.String("remoteAddress", conn.RemoteAddr().String())) return