neoneo-go/pkg/network/payload/inventory.go
Roman Khimov 5bf00db2c9 io: move BinReader/BinWriter there, redo Serializable with it
The logic here is that we'll have all binary encoding/decoding done via our io
package, which simplifies error handling. This functionality doesn't belong to
util, so it's moved.

This also expands BufBinWriter with Reset() method to fit the needs of core
package.
2019-09-16 23:39:51 +03:00

81 lines
1.8 KiB
Go

package payload
import (
"github.com/CityOfZion/neo-go/pkg/io"
"github.com/CityOfZion/neo-go/pkg/util"
)
// The node can broadcast the object information it owns by this message.
// The message can be sent automatically or can be used to answer getblock messages.
// InventoryType is the type of an object in the Inventory message.
type InventoryType uint8
// String implements the Stringer interface.
func (i InventoryType) String() string {
switch i {
case 0x01:
return "TX"
case 0x02:
return "block"
case 0xe0:
return "consensus"
default:
return "unknown inventory type"
}
}
// Valid returns true if the inventory (type) is known.
func (i InventoryType) Valid() bool {
return i == BlockType || i == TXType || i == ConsensusType
}
// List of valid InventoryTypes.
const (
TXType InventoryType = 0x01 // 1
BlockType InventoryType = 0x02 // 2
ConsensusType InventoryType = 0xe0 // 224
)
// Inventory payload
type Inventory struct {
// Type if the object hash.
Type InventoryType
// A list of hashes.
Hashes []util.Uint256
}
// NewInventory return a pointer to an Inventory.
func NewInventory(typ InventoryType, hashes []util.Uint256) *Inventory {
return &Inventory{
Type: typ,
Hashes: hashes,
}
}
// DecodeBinary implements the Payload interface.
func (p *Inventory) DecodeBinary(br *io.BinReader) error {
br.ReadLE(&p.Type)
listLen := br.ReadVarUint()
p.Hashes = make([]util.Uint256, listLen)
for i := 0; i < int(listLen); i++ {
br.ReadLE(&p.Hashes[i])
}
return br.Err
}
// EncodeBinary implements the Payload interface.
func (p *Inventory) EncodeBinary(bw *io.BinWriter) error {
bw.WriteLE(p.Type)
listLen := len(p.Hashes)
bw.WriteVarUint(uint64(listLen))
for i := 0; i < listLen; i++ {
bw.WriteLE(p.Hashes[i])
}
return bw.Err
}