Skip to content

Commit 2c505ef

Browse files
committed
p2p/discover: add NodeID.Pubkey
1 parent d344054 commit 2c505ef

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

‎p2p/discover/node.go‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@ import (
77
"errors"
88
"fmt"
99
"io"
10+
"math/big"
1011
"math/rand"
1112
"net"
1213
"net/url"
1314
"strconv"
1415
"strings"
1516
"time"
1617

18+
"github.com/ethereum/go-ethereum/crypto"
1719
"github.com/ethereum/go-ethereum/crypto/secp256k1"
1820
"github.com/ethereum/go-ethereum/rlp"
1921
)
@@ -187,6 +189,19 @@ func PubkeyID(pub *ecdsa.PublicKey) NodeID {
187189
return id
188190
}
189191

192+
// Pubkey returns the public key represented by the node ID.
193+
// It returns an error if the ID is not a point on the curve.
194+
func (id NodeID) Pubkey() (*ecdsa.PublicKey, error) {
195+
p := &ecdsa.PublicKey{Curve: crypto.S256(), X: new(big.Int), Y: new(big.Int)}
196+
half := len(id) / 2
197+
p.X.SetBytes(id[:half])
198+
p.Y.SetBytes(id[half:])
199+
if !p.Curve.IsOnCurve(p.X, p.Y) {
200+
return nil, errors.New("not a point on the S256 curve")
201+
}
202+
return p, nil
203+
}
204+
190205
// recoverNodeID computes the public key used to sign the
191206
// given hash from the signature.
192207
func recoverNodeID(hash, sig []byte) (id NodeID, err error) {

‎p2p/discover/node_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,24 @@ func TestNodeID_recover(t *testing.T) {
133133
if pub != recpub {
134134
t.Errorf("recovered wrong pubkey:\ngot: %v\nwant: %v", recpub, pub)
135135
}
136+
137+
ecdsa, err := pub.Pubkey()
138+
if err != nil {
139+
t.Errorf("Pubkey error: %v", err)
140+
}
141+
if !reflect.DeepEqual(ecdsa, &prv.PublicKey) {
142+
t.Errorf("Pubkey mismatch:\n got: %#v\n want: %#v", ecdsa, &prv.PublicKey)
143+
}
144+
}
145+
146+
func TestNodeID_pubkeyBad(t *testing.T) {
147+
ecdsa, err := NodeID{}.Pubkey()
148+
if err == nil {
149+
t.Error("expected error for zero ID")
150+
}
151+
if ecdsa != nil {
152+
t.Error("expected nil result")
153+
}
136154
}
137155

138156
func TestNodeID_distcmp(t *testing.T) {

0 commit comments

Comments
 (0)