@@ -70,6 +70,38 @@ func KeyFromStr(s string) (Key, error) {
70
70
return Key {}, fmt .Errorf ("Key unknown format length %d" , len (b ))
71
71
}
72
72
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
+
73
105
// KeyFromBytes decodes a binary bitcoin key. It returns the key and an error if there was an
74
106
// issue.
75
107
func KeyFromBytes (b []byte , net Network ) (Key , error ) {
@@ -130,13 +162,7 @@ func (k Key) Network() Network {
130
162
131
163
// SetString decodes a key from hex text.
132
164
func (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 )
140
166
}
141
167
142
168
// SetBytes decodes the key from bytes.
@@ -163,7 +189,7 @@ func (k Key) Bytes() []byte {
163
189
164
190
func (k * Key ) Deserialize (r io.Reader ) error {
165
191
b := make ([]byte , 33 )
166
- if _ , err := r . Read ( b ); err != nil {
192
+ if _ , err := io . ReadFull ( r , b ); err != nil {
167
193
return errors .Wrap (err , "key" )
168
194
}
169
195
@@ -213,7 +239,7 @@ func (k Key) MarshalJSON() ([]byte, error) {
213
239
214
240
// UnmarshalJSON converts from json.
215
241
func (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 ]))
217
243
}
218
244
219
245
// MarshalText returns the text encoding of the key.
@@ -228,13 +254,7 @@ func (k Key) MarshalText() ([]byte, error) {
228
254
// UnmarshalText parses a text encoded key and sets the value of this object.
229
255
// Implements encoding.TextUnmarshaler interface.
230
256
func (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 ))
238
258
}
239
259
240
260
// MarshalBinary returns the binary encoding of the key.
0 commit comments