Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix skademlia ID address race condition. #252

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions skademlia/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func (c *Client) ClosestPeers(opts ...DialOption) []*grpc.ClientConn {
var conns []*grpc.ClientConn

for i := range ids {
if conn, err := c.Dial(ids[i].address, opts...); err == nil {
if conn, err := c.Dial(ids[i].Address(), opts...); err == nil {
conns = append(conns, conn)
}
}
Expand Down Expand Up @@ -224,7 +224,7 @@ func (c *Client) getPeerID(conn *grpc.ClientConn, timeout time.Duration) (*ID, e
}

func (c *Client) DialContext(ctx context.Context, addr string) (*grpc.ClientConn, error) {
if addr == c.table.self.address {
if addr == c.table.self.Address() {
return nil, errors.New("attempted to dial self")
}

Expand Down Expand Up @@ -393,10 +393,8 @@ func (c *Client) Bootstrap() (results []*ID) {
}

func (c *Client) FindNode(target *ID, k int, a int, d int) (results []*ID) {
type request ID

type response struct {
requester *request
requester *ID
ids []*ID
}

Expand All @@ -419,14 +417,14 @@ func (c *Client) FindNode(target *ID, k int, a int, d int) (results []*ID) {

for _, lookup := range lookups { // Perform d parallel disjoint lookups.
go func(lookup queue.Queue) {
requests := make(chan *request, a)
requests := make(chan *ID, a)
responses := make(chan *response, a)

for i := 0; i < a; i++ { // Perform α queries in parallel per disjoint lookup.
go func() {
for id := range requests {
f := func() error {
conn, err := c.Dial(id.address, WithTimeout(3*time.Second))
conn, err := c.Dial(id.Address(), WithTimeout(3*time.Second))

if err != nil {
responses <- nil
Expand Down Expand Up @@ -470,7 +468,7 @@ func (c *Client) FindNode(target *ID, k int, a int, d int) (results []*ID) {

for lookup.Len() > 0 || pending > 0 {
for lookup.Len() > 0 && len(requests) < cap(requests) {
requests <- (*request)(lookup.PopFront().(*ID))
requests <- lookup.PopFront().(*ID)
pending++
}

Expand Down
30 changes: 22 additions & 8 deletions skademlia/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,15 @@ import (
"github.com/pkg/errors"
"golang.org/x/crypto/blake2b"
"io"
"sync"
)

type ID struct {
address string
publicKey edwards25519.PublicKey

sync.RWMutex

id, checksum, nonce [blake2b.Size256]byte
}

Expand All @@ -49,8 +52,11 @@ func NewID(address string, publicKey edwards25519.PublicKey, nonce [blake2b.Size
}
}

func (m ID) Address() string {
return m.address
func (m *ID) Address() string {
m.RLock()
t := m.address
m.RUnlock()
return t
}

func (m ID) PublicKey() edwards25519.PublicKey {
Expand All @@ -66,16 +72,24 @@ func (m ID) Nonce() [blake2b.Size256]byte {
}

func (m ID) String() string {
return fmt.Sprintf("%s[%x]", m.address, m.publicKey)
return fmt.Sprintf("%s[%x]", (&m).Address(), m.publicKey)
}

func (m *ID) SetAddress(address string) {
m.Lock()
m.address = address
m.Unlock()
}

func (m ID) Marshal() []byte {
buf := make([]byte, 2+len(m.address)+edwards25519.SizePublicKey+blake2b.Size256)
address := (&m).Address()

buf := make([]byte, 2+len(address)+edwards25519.SizePublicKey+blake2b.Size256)

binary.BigEndian.PutUint16(buf[0:2], uint16(len(m.address)))
copy(buf[2:2+len(m.address)], m.address)
copy(buf[2+len(m.address):2+len(m.address)+edwards25519.SizePublicKey], m.publicKey[:])
copy(buf[2+len(m.address)+edwards25519.SizePublicKey:2+len(m.address)+edwards25519.SizePublicKey+blake2b.Size256], m.nonce[:])
binary.BigEndian.PutUint16(buf[0:2], uint16(len(address)))
copy(buf[2:2+len(address)], address)
copy(buf[2+len(address):2+len(address)+edwards25519.SizePublicKey], m.publicKey[:])
copy(buf[2+len(address)+edwards25519.SizePublicKey:2+len(address)+edwards25519.SizePublicKey+blake2b.Size256], m.nonce[:])

return buf
}
Expand Down
2 changes: 1 addition & 1 deletion skademlia/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func (p Protocol) Server(info noise.Info, conn net.Conn) (net.Conn, error) {
p.client.logger.Printf("Client %s has connected to you", id)

go func() {
if _, err = p.client.Dial(id.address, WithTimeout(3*time.Second)); err != nil {
if _, err = p.client.Dial(id.Address(), WithTimeout(3*time.Second)); err != nil {
p.client.logger.Printf("Client %s was not able to be dialed back, closing connection", id)
_ = conn.Close()
} else {
Expand Down
3 changes: 1 addition & 2 deletions skademlia/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,7 @@ func (t *Table) Update(target *ID) error {
b.Lock()

// address might differ for same public key (checksum
id := found.Value.(*ID)
id.address = target.address
found.Value.(*ID).SetAddress(target.address)

b.MoveToFront(found)
b.Unlock()
Expand Down
18 changes: 14 additions & 4 deletions skademlia/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/perlin-network/noise/edwards25519"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/blake2b"
"sync"
"testing"
"testing/quick"
)
Expand Down Expand Up @@ -172,16 +173,25 @@ func TestUpdateSamePublicKey(t *testing.T) {
// we create new id with same public key but different address
addressToChange := "127.0.0.3"
updatedCopy := NewID(addressToChange, updated.publicKey, updated.nonce)
if !assert.NoError(t, table.Update(updatedCopy)) {
return
}

wg := sync.WaitGroup{}
// ensure that updating table (and id) safe to be done concurrently
wg.Add(1)
go func() {
defer wg.Done()
if !assert.NoError(t, table.Update(updatedCopy)) {
return
}
}()

found := table.FindClosest(rootID, 10)
if !assert.Equal(t, 1, len(found)) {
return
}

wg.Wait()

// we expect id in the table to have same public key but updated address
assert.Equal(t, updated.publicKey, found[0].publicKey)
assert.Equal(t, addressToChange, found[0].address)
assert.Equal(t, addressToChange, found[0].Address())
}