You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.7 KiB
68 lines
1.7 KiB
6 years ago
|
package identity
|
||
|
|
||
|
import (
|
||
6 years ago
|
"bytes"
|
||
6 years ago
|
"errors"
|
||
6 years ago
|
|
||
6 years ago
|
"github.com/harmony-one/harmony/api/proto"
|
||
6 years ago
|
)
|
||
|
|
||
6 years ago
|
// IdentityMessageTypeBytes is the number of bytes consensus message type occupies
|
||
6 years ago
|
const IdentityMessageTypeBytes = 1
|
||
6 years ago
|
|
||
6 years ago
|
// IDMessageType is the identity message type.
|
||
|
type IDMessageType byte
|
||
6 years ago
|
|
||
6 years ago
|
// Constants of IdentityMessageType.
|
||
6 years ago
|
const (
|
||
6 years ago
|
Identity IDMessageType = iota
|
||
6 years ago
|
// TODO: add more types
|
||
|
)
|
||
|
|
||
6 years ago
|
// MessageType ...
|
||
6 years ago
|
type MessageType int
|
||
|
|
||
6 years ago
|
// Constants of MessageType.
|
||
6 years ago
|
const (
|
||
6 years ago
|
Register MessageType = iota
|
||
6 years ago
|
Acknowledge
|
||
6 years ago
|
)
|
||
|
|
||
|
// Returns string name for the MessageType enum
|
||
|
func (msgType MessageType) String() string {
|
||
|
names := [...]string{
|
||
6 years ago
|
"Register",
|
||
6 years ago
|
"Acknowledge",
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
if msgType < Register || msgType > Acknowledge {
|
||
6 years ago
|
return "Unknown"
|
||
|
}
|
||
|
return names[msgType]
|
||
|
}
|
||
|
|
||
6 years ago
|
// GetIdentityMessageType Get the identity message type from the identity message
|
||
6 years ago
|
func GetIdentityMessageType(message []byte) (MessageType, error) {
|
||
|
if len(message) < 1 {
|
||
6 years ago
|
return 0, errors.New("failed to get identity message type: no data available")
|
||
6 years ago
|
}
|
||
|
return MessageType(message[0]), nil
|
||
|
}
|
||
|
|
||
|
// GetIdentityMessagePayload message payload from the identity message
|
||
|
func GetIdentityMessagePayload(message []byte) ([]byte, error) {
|
||
|
if len(message) < 2 {
|
||
6 years ago
|
return []byte{}, errors.New("failed to get identity message payload: no data available")
|
||
6 years ago
|
}
|
||
6 years ago
|
return message[IdentityMessageTypeBytes:], nil
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
6 years ago
|
// ConstructIdentityMessage concatenates msgType as one byte with payload, and return the whole byte array
|
||
6 years ago
|
func ConstructIdentityMessage(identityMessageType MessageType, payload []byte) []byte {
|
||
6 years ago
|
byteBuffer := bytes.NewBuffer([]byte{byte(proto.Identity)})
|
||
|
byteBuffer.WriteByte(byte(Identity))
|
||
6 years ago
|
byteBuffer.WriteByte(byte(identityMessageType))
|
||
|
byteBuffer.Write(payload)
|
||
|
return byteBuffer.Bytes()
|
||
|
}
|