github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/internal/when/handle_show.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  	"errors"
     9  
    10  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base"
    11  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/identifiers"
    12  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
    13  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/output"
    14  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/tslib"
    15  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/types"
    16  	"github.com/ethereum/go-ethereum"
    17  )
    18  
    19  func (opts *WhenOptions) HandleShow(rCtx *output.RenderCtx) error {
    20  	chain := opts.Globals.Chain
    21  
    22  	fetchData := func(modelChan chan types.Modeler, errorChan chan error) {
    23  		for _, br := range opts.BlockIds {
    24  			blockNums, err := br.ResolveBlocks(chain)
    25  			if err != nil {
    26  				errorChan <- err
    27  				if errors.Is(err, ethereum.NotFound) {
    28  					continue
    29  				}
    30  				rCtx.Cancel()
    31  				return
    32  			}
    33  
    34  			showProgress := opts.Globals.ShowProgress()
    35  			bar := logger.NewBar(logger.BarOptions{
    36  				Enabled: showProgress,
    37  				Total:   int64(len(blockNums)),
    38  			})
    39  
    40  			for _, bn := range blockNums {
    41  				block, err := opts.Conn.GetBlockHeaderByNumber(bn)
    42  				if err != nil {
    43  					errorChan <- err
    44  					if errors.Is(err, ethereum.NotFound) {
    45  						continue
    46  					}
    47  					rCtx.Cancel()
    48  					return
    49  				}
    50  				if br.StartType == identifiers.BlockHash && base.HexToHash(br.Orig) != block.Hash {
    51  					errorChan <- errors.New("block hash not found")
    52  					continue
    53  				}
    54  
    55  				nb, _ := tslib.FromBnToNamedBlock(chain, block.BlockNumber)
    56  				if nb == nil {
    57  					modelChan <- &types.NamedBlock{
    58  						BlockNumber: block.BlockNumber,
    59  						Timestamp:   block.Timestamp,
    60  					}
    61  				} else {
    62  					modelChan <- nb
    63  				}
    64  				bar.Tick()
    65  			}
    66  			bar.Finish(true)
    67  		}
    68  	}
    69  
    70  	return output.StreamMany(rCtx, fetchData, opts.Globals.OutputOpts())
    71  }