github.com/MetalBlockchain/metalgo@v1.11.9/vms/platformvm/warp/unsigned_message.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package warp
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/MetalBlockchain/metalgo/ids"
    10  	"github.com/MetalBlockchain/metalgo/utils/hashing"
    11  )
    12  
    13  // UnsignedMessage defines the standard format for an unsigned Warp message.
    14  type UnsignedMessage struct {
    15  	NetworkID     uint32 `serialize:"true"`
    16  	SourceChainID ids.ID `serialize:"true"`
    17  	Payload       []byte `serialize:"true"`
    18  
    19  	bytes []byte
    20  	id    ids.ID
    21  }
    22  
    23  // NewUnsignedMessage creates a new *UnsignedMessage and initializes it.
    24  func NewUnsignedMessage(
    25  	networkID uint32,
    26  	sourceChainID ids.ID,
    27  	payload []byte,
    28  ) (*UnsignedMessage, error) {
    29  	msg := &UnsignedMessage{
    30  		NetworkID:     networkID,
    31  		SourceChainID: sourceChainID,
    32  		Payload:       payload,
    33  	}
    34  	return msg, msg.Initialize()
    35  }
    36  
    37  // ParseUnsignedMessage converts a slice of bytes into an initialized
    38  // *UnsignedMessage.
    39  func ParseUnsignedMessage(b []byte) (*UnsignedMessage, error) {
    40  	msg := &UnsignedMessage{
    41  		bytes: b,
    42  		id:    hashing.ComputeHash256Array(b),
    43  	}
    44  	_, err := Codec.Unmarshal(b, msg)
    45  	return msg, err
    46  }
    47  
    48  // Initialize recalculates the result of Bytes().
    49  func (m *UnsignedMessage) Initialize() error {
    50  	bytes, err := Codec.Marshal(CodecVersion, m)
    51  	if err != nil {
    52  		return fmt.Errorf("couldn't marshal warp unsigned message: %w", err)
    53  	}
    54  	m.bytes = bytes
    55  	m.id = hashing.ComputeHash256Array(m.bytes)
    56  	return nil
    57  }
    58  
    59  // Bytes returns the binary representation of this message. It assumes that the
    60  // message is initialized from either New, Parse, or an explicit call to
    61  // Initialize.
    62  func (m *UnsignedMessage) Bytes() []byte {
    63  	return m.bytes
    64  }
    65  
    66  // ID returns an identifier for this message. It assumes that the
    67  // message is initialized from either New, Parse, or an explicit call to
    68  // Initialize.
    69  func (m *UnsignedMessage) ID() ids.ID {
    70  	return m.id
    71  }
    72  
    73  func (m *UnsignedMessage) String() string {
    74  	return fmt.Sprintf("UnsignedMessage(NetworkID = %d, SourceChainID = %s, Payload = %x)", m.NetworkID, m.SourceChainID, m.Payload)
    75  }