neoneo-go/pkg/wire/payload/minventory.go

115 lines
2.2 KiB
Go
Raw Normal View History

2019-02-25 22:44:14 +00:00
package payload
import (
"errors"
"io"
"github.com/CityOfZion/neo-go/pkg/wire/command"
"github.com/CityOfZion/neo-go/pkg/wire/util"
)
//InvType represents the enum of inventory types
2019-02-25 22:44:14 +00:00
type InvType uint8
const (
// InvTypeTx represents the transaction inventory type
InvTypeTx InvType = 0x01
// InvTypeBlock represents the block inventory type
InvTypeBlock InvType = 0x02
// InvTypeConsensus represents the consensus inventory type
2019-02-25 22:44:14 +00:00
InvTypeConsensus InvType = 0xe0
)
const maxHashes = 0x10000000
2019-02-25 22:44:14 +00:00
var errMaxHash = errors.New("max size For Hashes reached")
2019-02-25 22:44:14 +00:00
// InvMessage represents an Inventory message on the neo-network
2019-02-25 22:44:14 +00:00
type InvMessage struct {
cmd command.Type
Type InvType
Hashes []util.Uint256
}
//NewInvMessage returns an InvMessage object
2019-02-25 22:44:14 +00:00
func NewInvMessage(typ InvType) (*InvMessage, error) {
inv := &InvMessage{
command.Inv,
typ,
nil,
}
return inv, nil
}
func newAbstractInv(typ InvType, cmd command.Type) (*InvMessage, error) {
inv, err := NewInvMessage(typ)
if err != nil {
return nil, err
}
inv.cmd = cmd
return inv, nil
}
// AddHash adds a hash to the list of hashes
func (inv *InvMessage) AddHash(h util.Uint256) error {
if len(inv.Hashes)+1 > maxHashes {
return errMaxHash
2019-02-25 22:44:14 +00:00
}
inv.Hashes = append(inv.Hashes, h)
2019-02-25 22:44:14 +00:00
return nil
}
// AddHashes adds multiple hashes to the list of hashes
func (inv *InvMessage) AddHashes(hashes []util.Uint256) error {
2019-02-25 22:44:14 +00:00
var err error
for _, hash := range hashes {
err = inv.AddHash(hash)
2019-02-25 22:44:14 +00:00
if err != nil {
break
}
}
return err
}
// DecodePayload Implements Messager interface
func (inv *InvMessage) DecodePayload(r io.Reader) error {
2019-02-25 22:44:14 +00:00
br := &util.BinReader{R: r}
br.Read(&inv.Type)
2019-02-25 22:44:14 +00:00
listLen := br.VarUint()
inv.Hashes = make([]util.Uint256, listLen)
2019-02-25 22:44:14 +00:00
for i := 0; i < int(listLen); i++ {
br.Read(&inv.Hashes[i])
2019-02-25 22:44:14 +00:00
}
return nil
}
// EncodePayload Implements messager interface
func (inv *InvMessage) EncodePayload(w io.Writer) error {
2019-02-25 22:44:14 +00:00
bw := &util.BinWriter{W: w}
bw.Write(inv.Type)
2019-02-25 22:44:14 +00:00
lenhashes := len(inv.Hashes)
2019-02-25 22:44:14 +00:00
bw.VarUint(uint64(lenhashes))
for _, hash := range inv.Hashes {
2019-02-25 22:44:14 +00:00
bw.Write(hash)
}
return bw.Err
}
// Command Implements messager interface
func (inv *InvMessage) Command() command.Type {
return inv.cmd
2019-02-25 22:44:14 +00:00
}