Skip to content

Commit 56679df

Browse files
authored
Merge pull request ethereum#99 from ethersphere/network-testing-framework-id-encoding
p2p/discover: Fix NodeID text encoding
2 parents fe1d6d2 + ec1b254 commit 56679df

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

p2p/discover/node.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,21 @@ func (n NodeID) TerminalString() string {
245245
return hex.EncodeToString(n[:8])
246246
}
247247

248+
// MarshalText implements the encoding.TextMarshaler interface.
249+
func (n NodeID) MarshalText() ([]byte, error) {
250+
return []byte(hex.EncodeToString(n[:])), nil
251+
}
252+
253+
// UnmarshalText implements the encoding.TextUnmarshaler interface.
254+
func (n *NodeID) UnmarshalText(text []byte) error {
255+
id, err := HexID(string(text))
256+
if err != nil {
257+
return err
258+
}
259+
*n = id
260+
return nil
261+
}
262+
248263
// BytesID converts a byte slice to a NodeID
249264
func BytesID(b []byte) (NodeID, error) {
250265
var id NodeID

p2p/discover/node_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package discover
1818

1919
import (
20+
"bytes"
2021
"fmt"
2122
"math/big"
2223
"math/rand"
@@ -192,6 +193,35 @@ func TestHexID(t *testing.T) {
192193
}
193194
}
194195

196+
func TestNodeID_textEncoding(t *testing.T) {
197+
ref := NodeID{
198+
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10,
199+
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20,
200+
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30,
201+
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x40,
202+
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x50,
203+
0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x60,
204+
0x61, 0x62, 0x63, 0x64,
205+
}
206+
hex := "01020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"
207+
208+
text, err := ref.MarshalText()
209+
if err != nil {
210+
t.Fatal(err)
211+
}
212+
if !bytes.Equal(text, []byte(hex)) {
213+
t.Fatalf("text encoding did not match\nexpected: %s\ngot: %s", hex, text)
214+
}
215+
216+
id := new(NodeID)
217+
if err := id.UnmarshalText(text); err != nil {
218+
t.Fatal(err)
219+
}
220+
if *id != ref {
221+
t.Fatalf("text decoding did not match\nexpected: %s\ngot: %s", ref, id)
222+
}
223+
}
224+
195225
func TestNodeID_recover(t *testing.T) {
196226
prv := newkey()
197227
hash := make([]byte, 32)

0 commit comments

Comments
 (0)