idscheme_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package enode
  17. import (
  18. "bytes"
  19. "crypto/ecdsa"
  20. "encoding/hex"
  21. "math/big"
  22. "testing"
  23. "github.com/ethereum/go-ethereum/crypto"
  24. "github.com/ethereum/go-ethereum/p2p/enr"
  25. "github.com/ethereum/go-ethereum/rlp"
  26. "github.com/stretchr/testify/assert"
  27. "github.com/stretchr/testify/require"
  28. )
  29. var (
  30. privkey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
  31. pubkey = &privkey.PublicKey
  32. )
  33. func TestEmptyNodeID(t *testing.T) {
  34. var r enr.Record
  35. if addr := ValidSchemes.NodeAddr(&r); addr != nil {
  36. t.Errorf("wrong address on empty record: got %v, want %v", addr, nil)
  37. }
  38. require.NoError(t, SignV4(&r, privkey))
  39. expected := "a448f24c6d18e575453db13171562b71999873db5b286df957af199ec94617f7"
  40. assert.Equal(t, expected, hex.EncodeToString(ValidSchemes.NodeAddr(&r)))
  41. }
  42. // Checks that failure to sign leaves the record unmodified.
  43. func TestSignError(t *testing.T) {
  44. invalidKey := &ecdsa.PrivateKey{D: new(big.Int), PublicKey: *pubkey}
  45. var r enr.Record
  46. emptyEnc, _ := rlp.EncodeToBytes(&r)
  47. if err := SignV4(&r, invalidKey); err == nil {
  48. t.Fatal("expected error from SignV4")
  49. }
  50. newEnc, _ := rlp.EncodeToBytes(&r)
  51. if !bytes.Equal(newEnc, emptyEnc) {
  52. t.Fatal("record modified even though signing failed")
  53. }
  54. }
  55. // TestGetSetSecp256k1 tests encoding/decoding and setting/getting of the Secp256k1 key.
  56. func TestGetSetSecp256k1(t *testing.T) {
  57. var r enr.Record
  58. if err := SignV4(&r, privkey); err != nil {
  59. t.Fatal(err)
  60. }
  61. var pk Secp256k1
  62. require.NoError(t, r.Load(&pk))
  63. assert.EqualValues(t, pubkey, &pk)
  64. }