libs5-go/encoding/nodeid.go

64 lines
1.2 KiB
Go
Raw Normal View History

2024-01-03 13:36:23 +00:00
package encoding
2024-01-03 13:21:48 +00:00
import (
"bytes"
"errors"
"git.lumeweb.com/LumeWeb/libs5-go/internal/bases"
"git.lumeweb.com/LumeWeb/libs5-go/utils"
2024-01-03 13:21:48 +00:00
"github.com/multiformats/go-multibase"
)
var (
errorNotBase58BTC = errors.New("not a base58btc string")
)
2024-01-03 20:28:40 +00:00
type NodeIdCode = int
2024-01-03 13:21:48 +00:00
type NodeId struct {
bytes []byte
}
func (nodeId *NodeId) Bytes() []byte {
return nodeId.bytes
2024-01-03 13:21:48 +00:00
}
2024-01-03 13:36:23 +00:00
func NewNodeId(bytes []byte) *NodeId {
return &NodeId{bytes: bytes}
2024-01-03 13:21:48 +00:00
}
func DecodeNodeId(nodeId string) (*NodeId, error) {
2024-01-03 13:21:48 +00:00
encoding, ret, err := multibase.Decode(nodeId)
if err != nil {
return nil, err
}
if encoding != multibase.Base58BTC {
return nil, errorNotBase58BTC
}
2024-01-03 13:36:23 +00:00
return NewNodeId(ret), nil
2024-01-03 13:21:48 +00:00
}
func (nodeId *NodeId) Equals(other interface{}) bool {
if otherNodeId, ok := other.(*NodeId); ok {
return bytes.Equal(nodeId.bytes, otherNodeId.bytes)
2024-01-03 13:21:48 +00:00
}
return false
}
func (nodeId *NodeId) HashCode() int {
return utils.HashCode(nodeId.bytes[:4])
2024-01-03 13:21:48 +00:00
}
func (nodeId *NodeId) ToBase58() (string, error) {
return bases.ToBase58BTC(nodeId.bytes)
2024-01-03 13:21:48 +00:00
}
func (nodeId *NodeId) ToString() (string, error) {
return nodeId.ToBase58()
}
func (nodeId *NodeId) Raw() []byte {
return nodeId.bytes[1:]
}