Ori Newman fa16c30cf3
Implement bip32 (#1676)
* Implement bip32

* Unite private and public extended keys

* Change variable names

* Change test name and add comment

* Rename var name

* Rename ckd.go to child_key_derivation.go

* Rename ser32 -> serializeUint32

* Add PrivateKey method

* Rename Path -> DeriveFromPath

* Add comment to validateChecksum

* Remove redundant condition from parsePath

* Rename Fingerprint->ParentFingerprint

* Merge hardened and non-hardened paths in calcI

* Change fingerPrintFromPoint to method

* Move hash160 to hash.go

* Fix a bug in calcI

* Simplify doubleSha256

* Remove slice end bound

* Split long line

* Change KaspaMainnetPrivate/public to represent kprv/kpub

* Add comments

* Fix comment

* Copy base58 library to kaspad

* Add versions for all networks

* Change versions to hex

* Add comments

Co-authored-by: Svarog <feanorr@gmail.com>
Co-authored-by: Elichai Turkel <elichai.turkel@gmail.com>
2021-04-28 15:27:16 +03:00

59 lines
1.2 KiB
Go

package bip32
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"crypto/sha512"
"github.com/pkg/errors"
"golang.org/x/crypto/ripemd160"
"hash"
)
func newHMACWriter(key []byte) hmacWriter {
return hmacWriter{
Hash: hmac.New(sha512.New, key),
}
}
type hmacWriter struct {
hash.Hash
}
func (hw hmacWriter) InfallibleWrite(p []byte) {
_, err := hw.Write(p)
if err != nil {
panic(errors.Wrap(err, "writing to hmac should never fail"))
}
}
func calcChecksum(data []byte) []byte {
return doubleSha256(data)[:checkSumLen]
}
func doubleSha256(data []byte) []byte {
inner := sha256.Sum256(data)
outer := sha256.Sum256(inner[:])
return outer[:]
}
// validateChecksum validates that the last checkSumLen bytes of the
// given data are its valid checksum.
func validateChecksum(data []byte) error {
checksum := data[len(data)-checkSumLen:]
expectedChecksum := calcChecksum(data[:len(data)-checkSumLen])
if !bytes.Equal(expectedChecksum, checksum) {
return errors.Errorf("expected checksum %x but got %x", expectedChecksum, checksum)
}
return nil
}
func hash160(data []byte) []byte {
sha := sha256.New()
ripe := ripemd160.New()
sha.Write(data)
ripe.Write(sha.Sum(nil))
return ripe.Sum(nil)
}