@@ -70,6 +70,38 @@ func KeyFromStr(s string) (Key, error) {
7070 return Key {}, fmt .Errorf ("Key unknown format length %d" , len (b ))
7171}
7272
73+ func (k * Key ) DecodeString (s string ) error {
74+ b , err := decodeAddress (s )
75+ if err != nil {
76+ return err
77+ }
78+
79+ switch b [0 ] {
80+ case typeMainPrivKey :
81+ k .net = MainNet
82+ case typeTestPrivKey :
83+ k .net = TestNet
84+ default :
85+ return ErrBadKeyType
86+ }
87+
88+ if len (b ) == 34 {
89+ if b [len (b )- 1 ] != 0x01 {
90+ return fmt .Errorf ("Key not for compressed public : %x" , b [len (b )- 1 :])
91+ }
92+ b = b [1 :33 ]
93+ } else if len (b ) == 33 {
94+ b = b [1 :]
95+ }
96+
97+ if err := privateKeyIsValid (b ); err != nil {
98+ return err
99+ }
100+
101+ k .value .SetBytes (b )
102+ return nil
103+ }
104+
73105// KeyFromBytes decodes a binary bitcoin key. It returns the key and an error if there was an
74106// issue.
75107func KeyFromBytes (b []byte , net Network ) (Key , error ) {
@@ -130,13 +162,7 @@ func (k Key) Network() Network {
130162
131163// SetString decodes a key from hex text.
132164func (k * Key ) SetString (s string ) error {
133- nk , err := KeyFromStr (s )
134- if err != nil {
135- return err
136- }
137-
138- * k = nk
139- return nil
165+ return k .DecodeString (s )
140166}
141167
142168// SetBytes decodes the key from bytes.
@@ -163,7 +189,7 @@ func (k Key) Bytes() []byte {
163189
164190func (k * Key ) Deserialize (r io.Reader ) error {
165191 b := make ([]byte , 33 )
166- if _ , err := r . Read ( b ); err != nil {
192+ if _ , err := io . ReadFull ( r , b ); err != nil {
167193 return errors .Wrap (err , "key" )
168194 }
169195
@@ -213,7 +239,7 @@ func (k Key) MarshalJSON() ([]byte, error) {
213239
214240// UnmarshalJSON converts from json.
215241func (k * Key ) UnmarshalJSON (data []byte ) error {
216- return k .SetString (string (data [1 : len (data )- 1 ]))
242+ return k .DecodeString (string (data [1 : len (data )- 1 ]))
217243}
218244
219245// MarshalText returns the text encoding of the key.
@@ -228,13 +254,7 @@ func (k Key) MarshalText() ([]byte, error) {
228254// UnmarshalText parses a text encoded key and sets the value of this object.
229255// Implements encoding.TextUnmarshaler interface.
230256func (k * Key ) UnmarshalText (text []byte ) error {
231- b := make ([]byte , hex .DecodedLen (len (text )))
232- _ , err := hex .Decode (b , text )
233- if err != nil {
234- return err
235- }
236-
237- return k .SetBytes (b )
257+ return k .DecodeString (string (text ))
238258}
239259
240260// MarshalBinary returns the binary encoding of the key.
0 commit comments