github.com/MetalBlockchain/metalgo@v1.11.9/snow/engine/avalanche/vertex/test_vm.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package vertex
     5  
     6  import (
     7  	"context"
     8  	"errors"
     9  
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/MetalBlockchain/metalgo/ids"
    13  	"github.com/MetalBlockchain/metalgo/snow/consensus/snowstorm"
    14  	"github.com/MetalBlockchain/metalgo/snow/engine/snowman/block"
    15  )
    16  
    17  var (
    18  	errLinearize = errors.New("unexpectedly called Linearize")
    19  
    20  	_ LinearizableVM = (*TestVM)(nil)
    21  )
    22  
    23  type TestVM struct {
    24  	block.TestVM
    25  
    26  	CantLinearize, CantParse bool
    27  
    28  	LinearizeF func(context.Context, ids.ID) error
    29  	ParseTxF   func(context.Context, []byte) (snowstorm.Tx, error)
    30  }
    31  
    32  func (vm *TestVM) Default(cant bool) {
    33  	vm.TestVM.Default(cant)
    34  
    35  	vm.CantParse = cant
    36  }
    37  
    38  func (vm *TestVM) Linearize(ctx context.Context, stopVertexID ids.ID) error {
    39  	if vm.LinearizeF != nil {
    40  		return vm.LinearizeF(ctx, stopVertexID)
    41  	}
    42  	if vm.CantLinearize && vm.T != nil {
    43  		require.FailNow(vm.T, errLinearize.Error())
    44  	}
    45  	return errLinearize
    46  }
    47  
    48  func (vm *TestVM) ParseTx(ctx context.Context, b []byte) (snowstorm.Tx, error) {
    49  	if vm.ParseTxF != nil {
    50  		return vm.ParseTxF(ctx, b)
    51  	}
    52  	if vm.CantParse && vm.T != nil {
    53  		require.FailNow(vm.T, errParse.Error())
    54  	}
    55  	return nil, errParse
    56  }