File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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.
192207func recoverNodeID (hash , sig []byte ) (id NodeID , err error ) {
Original file line number Diff line number Diff line change @@ -133,6 +133,24 @@ func TestNodeID_recover(t *testing.T) {
133133 if pub != recpub {
134134 t .Errorf ("recovered wrong pubkey:\n got: %v\n want: %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
138156func TestNodeID_distcmp (t * testing.T ) {
You can’t perform that action at this time.
0 commit comments