github.com/Finschia/finschia-sdk@v0.48.1/client/rpc/block.go (about)

     1  package rpc
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strconv"
     7  
     8  	"github.com/spf13/cobra"
     9  
    10  	"github.com/Finschia/finschia-sdk/client"
    11  	"github.com/Finschia/finschia-sdk/client/flags"
    12  	"github.com/Finschia/finschia-sdk/codec/legacy"
    13  )
    14  
    15  // BlockCommand returns the verified block data for a given heights
    16  func BlockCommand() *cobra.Command {
    17  	cmd := &cobra.Command{
    18  		Use:   "block [height]",
    19  		Short: "Get verified data for a the block at given height",
    20  		Args:  cobra.MaximumNArgs(1),
    21  		RunE: func(cmd *cobra.Command, args []string) error {
    22  			clientCtx, err := client.GetClientQueryContext(cmd)
    23  			if err != nil {
    24  				return err
    25  			}
    26  			var height *int64
    27  
    28  			// optional height
    29  			if len(args) > 0 {
    30  				h, err := strconv.Atoi(args[0])
    31  				if err != nil {
    32  					return err
    33  				}
    34  				if h > 0 {
    35  					tmp := int64(h)
    36  					height = &tmp
    37  				}
    38  			}
    39  
    40  			output, err := getBlock(clientCtx, height)
    41  			if err != nil {
    42  				return err
    43  			}
    44  
    45  			fmt.Println(string(output))
    46  			return nil
    47  		},
    48  	}
    49  
    50  	cmd.Flags().StringP(flags.FlagNode, "n", "tcp://localhost:26657", "Node to connect to")
    51  
    52  	return cmd
    53  }
    54  
    55  func getBlock(clientCtx client.Context, height *int64) ([]byte, error) {
    56  	// get the node
    57  	node, err := clientCtx.GetNode()
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  
    62  	// header -> BlockchainInfo
    63  	// header, tx -> Block
    64  	// results -> BlockResults
    65  	res, err := node.Block(context.Background(), height)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  
    70  	return legacy.Cdc.MarshalJSON(res)
    71  }
    72  
    73  // get the current blockchain height
    74  func GetChainHeight(clientCtx client.Context) (int64, error) {
    75  	node, err := clientCtx.GetNode()
    76  	if err != nil {
    77  		return -1, err
    78  	}
    79  
    80  	status, err := node.Status(context.Background())
    81  	if err != nil {
    82  		return -1, err
    83  	}
    84  
    85  	height := status.SyncInfo.LatestBlockHeight
    86  	return height, nil
    87  }