checked missing files for inventory.

This commit is contained in:
anthdm 2018-01-28 08:05:35 +01:00
parent f28d8f9ab6
commit 68088d816c
4 changed files with 133 additions and 0 deletions

View file

@ -0,0 +1,63 @@
package payload
import (
"bytes"
"encoding/binary"
. "github.com/anthdm/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 getbloks 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 "block"
case 0x02:
return "TX"
case 0xe0:
return "consensus"
default:
return "unknown inventory type"
}
}
// List of valid InventoryTypes.
const (
BlockType InventoryType = 0x01 // 1
TXType = 0x02 // 2
ConsensusType = 0xe0 // 224
)
// Inventory payload
type Inventory struct {
// Type if the object hash.
Type InventoryType
// The hash of the object (uint256).
Hash Uint256
}
// UnmarshalBinary implements the Payloader interface.
func (p *Inventory) UnmarshalBinary(b []byte) error {
// TODO: what byte is [1:2] ?
// We have 1 byte for the type which is uint8 and 32 for the hash.
// There is 1 byte left over.
binary.Read(bytes.NewReader(b), binary.LittleEndian, &p.Type)
p.Hash.UnmarshalBinary(b[2:len(b)])
return nil
}
// MarshalBinary implements the Payloader interface.
func (p *Inventory) MarshalBinary() ([]byte, error) {
return nil, nil
}
// Size implements the Payloader interface.
func (p *Inventory) Size() uint32 {
return 1 + 1 + 32 // ?
}

16
pkg/util/random.go Normal file
View file

@ -0,0 +1,16 @@
package util
import (
"math/rand"
"time"
)
// RandUint32 return a random number between min and max.
func RandUint32(min, max int) uint32 {
n := min + rand.Intn(max-min)
return uint32(n)
}
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}

46
pkg/util/uint256.go Normal file
View file

@ -0,0 +1,46 @@
package util
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
)
// Uint256 ...
type Uint256 [32]uint8
// Uint256FromBytes return an Uint256 from a byte slice.
func Uint256FromBytes(b []byte) Uint256 {
if len(b) != 32 {
err := fmt.Sprintf("%d does not match the size of Uint256 (32 bytes)", len(b))
panic(err)
}
var val [32]uint8
for i := 0; i < 32; i++ {
val[i] = b[i]
}
return Uint256(val)
}
// UnmarshalBinary implements the Binary Unmarshaler interface.
func (u *Uint256) UnmarshalBinary(b []byte) error {
r := bytes.NewReader(b)
binary.Read(r, binary.LittleEndian, u)
return nil
}
// ToSlice return a byte slice of u.
func (u Uint256) ToSlice() []byte {
b := make([]byte, 32)
for i := 0; i < 32; i++ {
b[i] = byte(u[i])
}
return b
}
func (u Uint256) String() string {
return hex.EncodeToString(u.ToSlice())
}

8
pkg/util/uint256_test.go Normal file
View file

@ -0,0 +1,8 @@
package util
import (
"testing"
)
func TestUint256(t *testing.T) {
}