github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/monitor/truncate.go (about) 1 package monitor 2 3 import ( 4 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base" 5 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/filter" 6 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/types" 7 ) 8 9 func (mon *Monitor) TruncateTo(chain string, num uint32) (bool, error) { 10 err := mon.ReadMonitorHeader() 11 if err != nil { 12 return false, err 13 } 14 15 if apps, cnt, err := mon.ReadAndFilterAppearances(filter.NewEmptyFilter(), true /* withCount */); err != nil { 16 return false, err 17 18 } else if cnt == 0 { 19 return false, nil 20 21 } else { 22 var keep []types.AppRecord 23 for _, app := range apps { 24 if app.BlockNumber <= num { 25 keep = append(keep, types.AppRecord{ 26 BlockNumber: app.BlockNumber, 27 TransactionIndex: app.TransactionIndex, 28 }) 29 } 30 } 31 lastScanned := base.Min(num, mon.Header.LastScanned) 32 33 mon.Close() // so when we open it, it gets replaced 34 // Very important to note - if you use false for append, the header gets overwritten 35 // so ordering matters here and we need to write the header afterwards 36 if _, err := mon.WriteAppearances(keep, false /* append */); err != nil { 37 mon.Close() 38 return false, err 39 } 40 _ = mon.WriteMonHeader(mon.Deleted, lastScanned, true /* force */) 41 mon.Close() 42 43 return len(apps)-len(keep) > 0, nil 44 } 45 }