-
Notifications
You must be signed in to change notification settings - Fork 67
/
soft_key.go
358 lines (305 loc) · 8.35 KB
/
soft_key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package key
import (
"bufio"
"bytes"
"encoding/hex"
"errors"
"io"
"os"
"strings"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/cb58"
"github.com/ava-labs/avalanchego/utils/crypto/secp256k1"
"github.com/ava-labs/avalanchego/utils/formatting/address"
"github.com/ava-labs/avalanchego/vms/components/avax"
"github.com/ava-labs/avalanchego/vms/platformvm/txs"
"github.com/ava-labs/avalanchego/vms/secp256k1fx"
eth_crypto "github.com/ethereum/go-ethereum/crypto"
"go.uber.org/zap"
)
var (
ErrInvalidPrivateKey = errors.New("invalid private key")
ErrInvalidPrivateKeyLen = errors.New("invalid private key length (expect 64 bytes in hex)")
ErrInvalidPrivateKeyEnding = errors.New("invalid private key ending")
ErrInvalidPrivateKeyEncoding = errors.New("invalid private key encoding")
)
var _ Key = &SoftKey{}
type SoftKey struct {
privKey *secp256k1.PrivateKey
privKeyRaw []byte
privKeyEncoded string
pAddr string
keyChain *secp256k1fx.Keychain
}
const (
privKeyEncPfx = "PrivateKey-"
privKeySize = 64
rawEwoqPk = "ewoqjP7PxY4yr3iLTpLisriqt94hdyDFNgchSxGGztUrTXtNN"
EwoqPrivateKey = privKeyEncPfx + rawEwoqPk
)
var keyFactory = new(secp256k1.Factory)
type SOp struct {
privKey *secp256k1.PrivateKey
privKeyEncoded string
}
type SOpOption func(*SOp)
func (sop *SOp) applyOpts(opts []SOpOption) {
for _, opt := range opts {
opt(sop)
}
}
// To create a new key SoftKey with a pre-loaded private key.
func WithPrivateKey(privKey *secp256k1.PrivateKey) SOpOption {
return func(sop *SOp) {
sop.privKey = privKey
}
}
// To create a new key SoftKey with a pre-defined private key.
func WithPrivateKeyEncoded(privKey string) SOpOption {
return func(sop *SOp) {
sop.privKeyEncoded = privKey
}
}
func NewSoft(networkID uint32, opts ...SOpOption) (*SoftKey, error) {
ret := &SOp{}
ret.applyOpts(opts)
// set via "WithPrivateKeyEncoded"
if len(ret.privKeyEncoded) > 0 {
privKey, err := decodePrivateKey(ret.privKeyEncoded)
if err != nil {
return nil, err
}
// to not overwrite
if ret.privKey != nil &&
!bytes.Equal(ret.privKey.Bytes(), privKey.Bytes()) {
return nil, ErrInvalidPrivateKey
}
ret.privKey = privKey
}
// generate a new one
if ret.privKey == nil {
var err error
ret.privKey, err = keyFactory.NewPrivateKey()
if err != nil {
return nil, err
}
}
privKey := ret.privKey
privKeyEncoded, err := encodePrivateKey(ret.privKey)
if err != nil {
return nil, err
}
// double-check encoding is consistent
if ret.privKeyEncoded != "" &&
ret.privKeyEncoded != privKeyEncoded {
return nil, ErrInvalidPrivateKeyEncoding
}
keyChain := secp256k1fx.NewKeychain()
keyChain.Add(privKey)
m := &SoftKey{
privKey: privKey,
privKeyRaw: privKey.Bytes(),
privKeyEncoded: privKeyEncoded,
keyChain: keyChain,
}
// Parse HRP to create valid address
hrp := GetHRP(networkID)
m.pAddr, err = address.Format("P", hrp, m.privKey.PublicKey().Address().Bytes())
if err != nil {
return nil, err
}
return m, nil
}
// LoadSoft loads the private key from disk and creates the corresponding SoftKey.
func LoadSoft(networkID uint32, keyPath string) (*SoftKey, error) {
kb, err := os.ReadFile(keyPath)
if err != nil {
return nil, err
}
// in case, it's already encoded
k, err := NewSoft(networkID, WithPrivateKeyEncoded(string(kb)))
if err == nil {
return k, nil
}
r := bufio.NewReader(bytes.NewBuffer(kb))
buf := make([]byte, privKeySize)
n, err := readASCII(buf, r)
if err != nil {
return nil, err
}
if n != len(buf) {
return nil, ErrInvalidPrivateKeyLen
}
if err := checkKeyFileEnd(r); err != nil {
return nil, err
}
skBytes, err := hex.DecodeString(string(buf))
if err != nil {
return nil, err
}
privKey, err := keyFactory.ToPrivateKey(skBytes)
if err != nil {
return nil, err
}
return NewSoft(networkID, WithPrivateKey(privKey))
}
// readASCII reads into 'buf', stopping when the buffer is full or
// when a non-printable control character is encountered.
func readASCII(buf []byte, r io.ByteReader) (n int, err error) {
for ; n < len(buf); n++ {
buf[n], err = r.ReadByte()
switch {
case errors.Is(err, io.EOF) || buf[n] < '!':
return n, nil
case err != nil:
return n, err
}
}
return n, nil
}
const fileEndLimit = 1
// checkKeyFileEnd skips over additional newlines at the end of a key file.
func checkKeyFileEnd(r io.ByteReader) error {
for idx := 0; ; idx++ {
b, err := r.ReadByte()
switch {
case errors.Is(err, io.EOF):
return nil
case err != nil:
return err
case b != '\n' && b != '\r':
return ErrInvalidPrivateKeyEnding
case idx > fileEndLimit:
return ErrInvalidPrivateKeyLen
}
}
}
func encodePrivateKey(pk *secp256k1.PrivateKey) (string, error) {
privKeyRaw := pk.Bytes()
enc, err := cb58.Encode(privKeyRaw)
if err != nil {
return "", err
}
return privKeyEncPfx + enc, nil
}
func decodePrivateKey(enc string) (*secp256k1.PrivateKey, error) {
rawPk := strings.Replace(enc, privKeyEncPfx, "", 1)
skBytes, err := cb58.Decode(rawPk)
if err != nil {
return nil, err
}
privKey, err := keyFactory.ToPrivateKey(skBytes)
if err != nil {
return nil, err
}
return privKey, nil
}
func (m *SoftKey) C() string {
ecdsaPrv := m.privKey.ToECDSA()
pub := ecdsaPrv.PublicKey
addr := eth_crypto.PubkeyToAddress(pub)
return addr.String()
}
// Returns the KeyChain
func (m *SoftKey) KeyChain() *secp256k1fx.Keychain {
return m.keyChain
}
// Returns the private key.
func (m *SoftKey) Key() *secp256k1.PrivateKey {
return m.privKey
}
// Returns the private key in raw bytes.
func (m *SoftKey) Raw() []byte {
return m.privKeyRaw
}
// Returns the private key encoded in CB58 and "PrivateKey-" prefix.
func (m *SoftKey) Encode() string {
return m.privKeyEncoded
}
// Saves the private key to disk with hex encoding.
func (m *SoftKey) Save(p string) error {
k := hex.EncodeToString(m.privKeyRaw)
return os.WriteFile(p, []byte(k), fsModeWrite)
}
func (m *SoftKey) P() []string {
return []string{m.pAddr}
}
func (m *SoftKey) Spends(outputs []*avax.UTXO, opts ...OpOption) (
totalBalanceToSpend uint64,
inputs []*avax.TransferableInput,
signers [][]ids.ShortID,
) {
ret := &Op{}
ret.applyOpts(opts)
for _, out := range outputs {
input, psigners, err := m.spend(out, ret.time)
if err != nil {
zap.L().Warn("cannot spend with current key", zap.Error(err))
continue
}
totalBalanceToSpend += input.Amount()
inputs = append(inputs, &avax.TransferableInput{
UTXOID: out.UTXOID,
Asset: out.Asset,
In: input,
})
// Convert to ids.ShortID to adhere with interface
pksigners := make([]ids.ShortID, len(psigners))
for i, psigner := range psigners {
pksigners[i] = psigner.PublicKey().Address()
}
signers = append(signers, pksigners)
if ret.targetAmount > 0 &&
totalBalanceToSpend > ret.targetAmount+ret.feeDeduct {
break
}
}
SortTransferableInputsWithSigners(inputs, signers)
return totalBalanceToSpend, inputs, signers
}
func (m *SoftKey) spend(output *avax.UTXO, time uint64) (
input avax.TransferableIn,
signers []*secp256k1.PrivateKey,
err error,
) {
// "time" is used to check whether the key owner
// is still within the lock time (thus can't spend).
inputf, psigners, err := m.keyChain.Spend(output.Out, time)
if err != nil {
return nil, nil, err
}
var ok bool
input, ok = inputf.(avax.TransferableIn)
if !ok {
return nil, nil, ErrInvalidType
}
return input, psigners, nil
}
const fsModeWrite = 0o600
func (m *SoftKey) Addresses() []ids.ShortID {
return []ids.ShortID{m.privKey.PublicKey().Address()}
}
func (m *SoftKey) Sign(pTx *txs.Tx, signers [][]ids.ShortID) error {
privsigners := make([][]*secp256k1.PrivateKey, len(signers))
for i, inputSigners := range signers {
privsigners[i] = make([]*secp256k1.PrivateKey, len(inputSigners))
for j, signer := range inputSigners {
if signer != m.privKey.PublicKey().Address() {
// Should never happen
return ErrCantSpend
}
privsigners[i][j] = m.privKey
}
}
return pTx.Sign(txs.Codec, privsigners)
}
func (m *SoftKey) Match(owners *secp256k1fx.OutputOwners, time uint64) ([]uint32, []ids.ShortID, bool) {
indices, privs, ok := m.keyChain.Match(owners, time)
pks := make([]ids.ShortID, len(privs))
for i, priv := range privs {
pks[i] = priv.PublicKey().Address()
}
return indices, pks, ok
}