github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/internal/when/handle_ts_update.go (about) 1 // Copyright 2021 The TrueBlocks Authors. All rights reserved. 2 // Use of this source code is governed by a license that can 3 // be found in the LICENSE file. 4 5 package whenPkg 6 7 import ( 8 "fmt" 9 10 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger" 11 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/output" 12 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/tslib" 13 ) 14 15 // HandleTimestampsUpdate update the timestamp file to the latest block 16 func (opts *WhenOptions) HandleTimestampsUpdate(rCtx *output.RenderCtx) error { 17 chain := opts.Globals.Chain 18 19 if opts.Globals.TestMode { 20 logger.Warn("Update option not tested.") 21 return nil 22 } 23 24 cnt, err := tslib.NTimestamps(chain) 25 if err != nil { 26 return err 27 } 28 29 meta, err := opts.Conn.GetMetaData(false) 30 if err != nil { 31 return err 32 } 33 34 if cnt >= meta.Latest { 35 logger.Info("Timestamp file is up to date.") 36 return nil 37 } 38 39 timestamps := make([]tslib.TimestampRecord, 0, meta.Latest-cnt+2) 40 41 logger.Info("Updating timestamps file from", cnt, "to", meta.Latest, fmt.Sprintf("(%d blocks)", (meta.Latest-cnt))) 42 for bn := cnt; bn < meta.Latest; bn++ { 43 block, _ := opts.Conn.GetBlockHeaderByNumber(bn) 44 record := tslib.TimestampRecord{Bn: uint32(block.BlockNumber), Ts: uint32(block.Timestamp)} 45 timestamps = append(timestamps, record) 46 logger.Progress(bn%23 == 0, "Adding block", bn, "of", meta.Latest, "to timestamp array") 47 if bn%1000 == 0 { 48 logger.Info("Writing...", len(timestamps), "timestamps at block", bn, " ") 49 _ = tslib.Append(chain, timestamps) 50 timestamps = []tslib.TimestampRecord{} 51 } 52 } 53 54 if len(timestamps) > 0 { 55 logger.Info("Writing...", len(timestamps), "timestamps at block", meta.Latest, " ") 56 _ = tslib.Append(chain, timestamps) 57 } 58 59 return nil 60 }