github.com/google/trillian-examples@v0.0.0-20240520080811-0d40d35cef0e/binary_transparency/firmware/cmd/ft_witness/internal/ws/store.go (about) 1 // Copyright 2021 Google LLC. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package ws contains a Witness Store backed by a file. 16 package ws 17 18 import ( 19 "fmt" 20 "os" 21 "sync" 22 ) 23 24 const ( 25 fileMask = 0755 26 ) 27 28 // Storage is a Witness Storage intended for storing witness checkpoints. 29 // Currently a simple file is used as a storage mechanism 30 type Storage struct { 31 fp string 32 storeLock sync.Mutex 33 } 34 35 // NewStorage creates a new WS that uses the given file as DB backend. 36 // The DB will be initialized if needed. 37 func NewStorage(fp string) (*Storage, error) { 38 ws := &Storage{ 39 fp: fp, 40 } 41 return ws, ws.init() 42 } 43 44 // init creates the file storage 45 func (ws *Storage) init() error { 46 // Check if the file exists, if not create one 47 f, err := os.OpenFile(ws.fp, os.O_RDWR|os.O_CREATE, os.ModePerm) 48 if err != nil { 49 return fmt.Errorf("failed to open file: %w", err) 50 } 51 if err := f.Close(); err != nil { 52 return fmt.Errorf("failed to close file: %w", err) 53 } 54 return nil 55 } 56 57 // StoreCP saves the given checkpoint into DB. 58 func (ws *Storage) StoreCP(wcp []byte) error { 59 ws.storeLock.Lock() 60 defer ws.storeLock.Unlock() 61 62 return os.WriteFile(ws.fp, wcp, fileMask) 63 } 64 65 // RetrieveCP gets the checkpoint previously stored. 66 func (ws *Storage) RetrieveCP() ([]byte, error) { 67 ws.storeLock.Lock() 68 defer ws.storeLock.Unlock() 69 return os.ReadFile(ws.fp) 70 }