code.vegaprotocol.io/vega@v0.79.0/datanode/entities/checkpoint.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package entities
    17  
    18  import (
    19  	"encoding/json"
    20  	"fmt"
    21  	"time"
    22  
    23  	v2 "code.vegaprotocol.io/vega/protos/data-node/api/v2"
    24  	eventspb "code.vegaprotocol.io/vega/protos/vega/events/v1"
    25  )
    26  
    27  type Checkpoint struct {
    28  	Hash        string
    29  	BlockHash   string
    30  	BlockHeight int64
    31  	TxHash      TxHash
    32  	VegaTime    time.Time
    33  	SeqNum      uint64
    34  }
    35  
    36  func (cp *Checkpoint) ToProto() *v2.Checkpoint {
    37  	pcp := v2.Checkpoint{
    38  		Hash:      cp.Hash,
    39  		BlockHash: cp.BlockHash,
    40  		AtBlock:   uint64(cp.BlockHeight),
    41  	}
    42  	return &pcp
    43  }
    44  
    45  func (cp Checkpoint) Cursor() *Cursor {
    46  	return NewCursor(CheckpointCursor{BlockHeight: cp.BlockHeight}.String())
    47  }
    48  
    49  func (cp Checkpoint) ToProtoEdge(_ ...any) (*v2.CheckpointEdge, error) {
    50  	return &v2.CheckpointEdge{
    51  		Node:   cp.ToProto(),
    52  		Cursor: cp.Cursor().Encode(),
    53  	}, nil
    54  }
    55  
    56  func CheckpointFromProto(cpe *eventspb.CheckpointEvent, txHash TxHash) (Checkpoint, error) {
    57  	cp := Checkpoint{
    58  		Hash:        cpe.Hash,
    59  		BlockHash:   cpe.BlockHash,
    60  		BlockHeight: int64(cpe.BlockHeight),
    61  		TxHash:      txHash,
    62  	}
    63  	return cp, nil
    64  }
    65  
    66  type CheckpointCursor struct {
    67  	BlockHeight int64 `json:"blockHeight"`
    68  }
    69  
    70  func (cp CheckpointCursor) String() string {
    71  	bs, err := json.Marshal(cp)
    72  	if err != nil {
    73  		panic(fmt.Errorf("couldn't marshal CheckpointCursor: %w", err))
    74  	}
    75  	return string(bs)
    76  }
    77  
    78  func (cp *CheckpointCursor) Parse(cursorString string) error {
    79  	if cursorString == "" {
    80  		return nil
    81  	}
    82  	return json.Unmarshal([]byte(cursorString), cp)
    83  }