muun-recovery/vendor/github.com/muun/libwallet/challenge_public_key.go

66 lines
1.7 KiB
Go
Raw Normal View History

2019-10-01 12:22:30 -03:00
package libwallet
import (
"bytes"
"encoding/binary"
2021-01-29 18:51:08 -03:00
"fmt"
2019-10-01 12:22:30 -03:00
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcutil/base58"
)
type ChallengePublicKey struct {
pubKey *btcec.PublicKey
}
func NewChallengePublicKeyFromSerialized(serializedKey []byte) (*ChallengePublicKey, error) {
pubKey, err := btcec.ParsePubKey(serializedKey, btcec.S256())
if err != nil {
return nil, err
}
return &ChallengePublicKey{pubKey}, nil
}
func (k *ChallengePublicKey) EncryptKey(privKey *HDPrivateKey, recoveryCodeSalt []byte, birthday int) (string, error) {
const (
2020-11-09 10:05:29 -03:00
chainCodeStart = 13
2019-10-01 12:22:30 -03:00
chainCodeLength = 32
2020-11-09 10:05:29 -03:00
privKeyStart = 46
privKeyLength = 32
2019-10-01 12:22:30 -03:00
)
rawHDKey := base58.Decode(privKey.String())
plaintext := make([]byte, 0)
plaintext = append(plaintext, rawHDKey[privKeyStart:privKeyStart+privKeyLength]...)
plaintext = append(plaintext, rawHDKey[chainCodeStart:chainCodeStart+chainCodeLength]...)
if len(plaintext) != 64 {
2021-01-29 18:51:08 -03:00
return "", fmt.Errorf("failed to encrypt key: expected payload of 64 bytes, found %v", len(plaintext))
2019-10-01 12:22:30 -03:00
}
2020-11-09 10:05:29 -03:00
pubEph, ciphertext, err := encryptWithPubKey(k.pubKey, plaintext)
2019-10-01 12:22:30 -03:00
if err != nil {
2020-11-09 10:05:29 -03:00
return "", err
2019-10-01 12:22:30 -03:00
}
birthdayBytes := make([]byte, 2)
binary.BigEndian.PutUint16(birthdayBytes, uint16(birthday))
2020-11-09 10:05:29 -03:00
if len(recoveryCodeSalt) == 0 {
// Fill the salt with zeros to maintain the encrypted keys format
recoveryCodeSalt = make([]byte, 8)
}
result := make([]byte, 0, 1+2+serializedPublicKeyLength+len(ciphertext)+len(recoveryCodeSalt))
2019-10-01 12:22:30 -03:00
buf := bytes.NewBuffer(result)
buf.WriteByte(2)
buf.Write(birthdayBytes)
2020-11-09 10:05:29 -03:00
buf.Write(pubEph.SerializeCompressed())
2019-10-01 12:22:30 -03:00
buf.Write(ciphertext)
buf.Write(recoveryCodeSalt)
return base58.Encode(buf.Bytes()), nil
2020-11-09 10:05:29 -03:00
}