github.com/mavryk-network/mvgo@v1.19.9/codec/ballot.go (about)

     1  // Copyright (c) 2020-2022 Blockwatch Data Inc.
     2  // Author: alex@blockwatch.cc
     3  
     4  package codec
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/binary"
     9  	"strconv"
    10  
    11  	"github.com/mavryk-network/mvgo/mavryk"
    12  )
    13  
    14  // Ballot represents "ballot" operation
    15  type Ballot struct {
    16  	Simple
    17  	Source   mavryk.Address      `json:"source"`
    18  	Period   int32               `json:"period"`
    19  	Proposal mavryk.ProtocolHash `json:"proposal"`
    20  	Ballot   mavryk.BallotVote   `json:"ballot"`
    21  }
    22  
    23  func (o Ballot) Kind() mavryk.OpType {
    24  	return mavryk.OpTypeBallot
    25  }
    26  
    27  func (o Ballot) MarshalJSON() ([]byte, error) {
    28  	buf := bytes.NewBuffer(nil)
    29  	buf.WriteByte('{')
    30  	buf.WriteString(`"kind":`)
    31  	buf.WriteString(strconv.Quote(o.Kind().String()))
    32  	buf.WriteString(`,"source":`)
    33  	buf.WriteString(strconv.Quote(o.Source.String()))
    34  	buf.WriteString(`,"period":`)
    35  	buf.WriteString(strconv.Itoa(int(o.Period)))
    36  	buf.WriteString(`,"proposal":`)
    37  	buf.WriteString(strconv.Quote(o.Proposal.String()))
    38  	buf.WriteString(`,"ballot":`)
    39  	buf.WriteString(strconv.Quote(o.Ballot.String()))
    40  	buf.WriteByte('}')
    41  	return buf.Bytes(), nil
    42  }
    43  
    44  func (o Ballot) EncodeBuffer(buf *bytes.Buffer, p *mavryk.Params) error {
    45  	buf.WriteByte(o.Kind().TagVersion(p.OperationTagsVersion))
    46  	buf.Write(o.Source.Encode())
    47  	binary.Write(buf, enc, o.Period)
    48  	buf.Write(o.Proposal.Bytes())
    49  	buf.WriteByte(o.Ballot.Tag())
    50  	return nil
    51  }
    52  
    53  func (o *Ballot) DecodeBuffer(buf *bytes.Buffer, p *mavryk.Params) (err error) {
    54  	if err = ensureTagAndSize(buf, o.Kind(), p.OperationTagsVersion); err != nil {
    55  		return
    56  	}
    57  	if err = o.Source.Decode(buf.Next(21)); err != nil {
    58  		return
    59  	}
    60  	o.Period, err = readInt32(buf.Next(4))
    61  	if err != nil {
    62  		return
    63  	}
    64  	if err = o.Proposal.UnmarshalBinary(buf.Next(32)); err != nil {
    65  		return
    66  	}
    67  	if err = o.Ballot.UnmarshalBinary(buf.Next(1)); err != nil {
    68  		return
    69  	}
    70  	return nil
    71  }
    72  
    73  func (o Ballot) MarshalBinary() ([]byte, error) {
    74  	buf := bytes.NewBuffer(nil)
    75  	err := o.EncodeBuffer(buf, mavryk.DefaultParams)
    76  	return buf.Bytes(), err
    77  }
    78  
    79  func (o *Ballot) UnmarshalBinary(data []byte) error {
    80  	return o.DecodeBuffer(bytes.NewBuffer(data), mavryk.DefaultParams)
    81  }