github.com/ava-labs/avalanchego@v1.11.11/network/p2p/gossip/test_gossip.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package gossip
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/ava-labs/avalanchego/ids"
    10  )
    11  
    12  var (
    13  	_ Gossipable          = (*testTx)(nil)
    14  	_ Set[*testTx]        = (*testSet)(nil)
    15  	_ Marshaller[*testTx] = (*testMarshaller)(nil)
    16  )
    17  
    18  type testTx struct {
    19  	id ids.ID
    20  }
    21  
    22  func (t *testTx) GossipID() ids.ID {
    23  	return t.id
    24  }
    25  
    26  type testMarshaller struct{}
    27  
    28  func (testMarshaller) MarshalGossip(tx *testTx) ([]byte, error) {
    29  	return tx.id[:], nil
    30  }
    31  
    32  func (testMarshaller) UnmarshalGossip(bytes []byte) (*testTx, error) {
    33  	id, err := ids.ToID(bytes)
    34  	return &testTx{
    35  		id: id,
    36  	}, err
    37  }
    38  
    39  type testSet struct {
    40  	txs   map[ids.ID]*testTx
    41  	bloom *BloomFilter
    42  	onAdd func(tx *testTx)
    43  }
    44  
    45  func (t *testSet) Add(gossipable *testTx) error {
    46  	if _, ok := t.txs[gossipable.id]; ok {
    47  		return fmt.Errorf("%s already present", gossipable.id)
    48  	}
    49  
    50  	t.txs[gossipable.id] = gossipable
    51  	t.bloom.Add(gossipable)
    52  	if t.onAdd != nil {
    53  		t.onAdd(gossipable)
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  func (t *testSet) Has(gossipID ids.ID) bool {
    60  	_, ok := t.txs[gossipID]
    61  	return ok
    62  }
    63  
    64  func (t *testSet) Iterate(f func(gossipable *testTx) bool) {
    65  	for _, tx := range t.txs {
    66  		if !f(tx) {
    67  			return
    68  		}
    69  	}
    70  }
    71  
    72  func (t *testSet) GetFilter() ([]byte, []byte) {
    73  	return t.bloom.Marshal()
    74  }