github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/beneficiary/local_storage.go (about) 1 /* 2 * Copyright (C) 2023 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package beneficiary 19 20 import ( 21 "strings" 22 "time" 23 24 "github.com/asdine/storm/v3" 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/pkg/errors" 27 ) 28 29 const ( 30 bucket = "beneficiary-address" 31 ) 32 33 // ErrInvalidAddress represents invalid address error 34 var ( 35 ErrInvalidAddress = errors.New("invalid address") 36 ErrNotFound = errors.New("beneficiary not found") 37 ) 38 39 type localStorage interface { 40 Store(bucket string, data interface{}) error 41 GetOneByField(bucket string, fieldName string, key interface{}, to interface{}) error 42 } 43 44 // BeneficiaryStorage handles storing of beneficiary address 45 type BeneficiaryStorage interface { 46 Address(identity string) (string, error) 47 Save(identity, address string) error 48 } 49 50 // AddressStorage handles storing of beneficiary address 51 type AddressStorage struct { 52 storage localStorage 53 } 54 55 // NewAddressStorage constructor 56 func NewAddressStorage(storage localStorage) *AddressStorage { 57 return &AddressStorage{ 58 storage: storage, 59 } 60 } 61 62 // Save beneficiary address for identity 63 func (as *AddressStorage) Save(identity, address string) error { 64 if !common.IsHexAddress(address) { 65 return ErrInvalidAddress 66 } 67 68 store := &storedBeneficiary{ 69 ID: strings.ToLower(identity), 70 Beneficiary: address, 71 LastUpdated: time.Now().UTC(), 72 } 73 return as.storage.Store(bucket, store) 74 } 75 76 // Address retrieve beneficiary address for identity 77 func (as *AddressStorage) Address(identity string) (string, error) { 78 result := &storedBeneficiary{} 79 err := as.storage.GetOneByField(bucket, "ID", strings.ToLower(identity), result) 80 if err != nil { 81 if errors.Is(err, storm.ErrNotFound) { 82 return "", ErrNotFound 83 } 84 return "", err 85 } 86 87 return result.Beneficiary, nil 88 } 89 90 type storedBeneficiary struct { 91 ID string `storm:"id"` 92 Beneficiary string 93 LastUpdated time.Time 94 }