node rpc Start & Ping, add rpc-test (client), add ID marshalers

This commit is contained in:
arnaucube
2019-12-07 20:03:50 +01:00
parent a698128605
commit 0e39e2facb
9 changed files with 192 additions and 3 deletions

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"crypto/rand"
"encoding/hex"
"fmt"
)
type ID [B]byte
@@ -23,6 +24,23 @@ func (id ID) String() string {
return hex.EncodeToString(id[:])
}
func (id ID) MarshalText() ([]byte, error) {
return []byte(hex.EncodeToString(id[:])), nil
}
func (id *ID) UnmarshalText(data []byte) error {
fmt.Println("UNMARSHAL")
fmt.Println("d", string(data))
var err error
var idFromStr ID
idFromStr, err = IDFromString(string(data))
if err != nil {
return err
}
copy(id[:], idFromStr[:])
return nil
}
func IDFromString(s string) (ID, error) {
b, err := hex.DecodeString(s)
if err != nil {

View File

@@ -1,6 +1,8 @@
package kademlia
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
@@ -19,6 +21,26 @@ func TestNewID(t *testing.T) {
assert.Equal(t, "0fd85ddddf15aeec2d5d8b01b013dbca030a18d7", idA.String())
}
func TestIDMarshalers(t *testing.T) {
id, err := IDFromString("0fd85ddddf15aeec2d5d8b01b013dbca030a18d7")
assert.Nil(t, err)
idStr, err := json.Marshal(id)
assert.Nil(t, err)
assert.Equal(t, "\"0fd85ddddf15aeec2d5d8b01b013dbca030a18d7\"", string(idStr))
fmt.Println("idStr", string(idStr))
var idParsed ID
err = json.Unmarshal(idStr, &idParsed)
assert.Nil(t, err)
assert.Equal(t, id, idParsed)
var idParsed2 ID
err = json.Unmarshal([]byte("\"0fd85ddddf15aeec2d5d8b01b013dbca030a18d7\""), &idParsed2)
assert.Nil(t, err)
assert.Equal(t, id, idParsed2)
}
func TestIDCmp(t *testing.T) {
idA, err := IDFromString("0fd85ddddf15aeec2d5d8b01b013dbca030a18d7")
assert.Nil(t, err)

View File

@@ -3,6 +3,8 @@ package kademlia
import (
"math/bits"
"strconv"
log "github.com/sirupsen/logrus"
)
const (
@@ -14,6 +16,7 @@ const (
type ListedNode struct {
ID ID
Addr string
Port string
}
type Kademlia struct {
@@ -60,6 +63,7 @@ func (kad *Kademlia) Update(o ListedNode) {
kb := kad.KBuckets[k]
if len(kb) >= KBucketSize {
// if n.KBuckets[k] is alrady full, perform ping of the first element
log.Debug("node.KBuckets[k] already full, performing ping to node.KBuckets[0]")
kad.Ping(k, o)
return
}
@@ -68,10 +72,12 @@ func (kad *Kademlia) Update(o ListedNode) {
if exist {
// update position of o to the bottom
kad.KBuckets[k] = moveToBottom(kad.KBuckets[k], pos)
log.Debug("ListedNode already exists, moved to bottom")
return
}
// not exists, add it to the kBucket
kad.KBuckets[k] = append(kad.KBuckets[k], o)
log.Debug("ListedNode not exists, added to the bottom")
return
}