forked from mit-dci/lit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
derive.go
71 lines (61 loc) · 1.7 KB
/
derive.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
package portxo
import (
"fmt"
"math/big"
"github.com/adiabat/btcd/btcec"
"github.com/adiabat/btcutil/hdkeychain"
)
// DerivePrivateKey returns the private key for a utxo based on a master key
func (kg *KeyGen) DerivePrivateKey(
m *hdkeychain.ExtendedKey) (*btcec.PrivateKey, error) {
var err error
var empty [32]byte
if m == nil {
return nil, fmt.Errorf("nil master key")
}
// there might be a private key here, but it can't be "derived"
if kg.Depth == 0 {
return nil, fmt.Errorf("no key derivation path")
}
currentKey := m
// this doesn't check for depth > 5, which is kindof invalid...
for i, step := range kg.Step {
if uint8(i) == kg.Depth {
break
}
currentKey, err = currentKey.Child(step)
if err != nil {
return nil, err
}
}
// get private key from the final derived child key
derivedPrivKey, err := currentKey.ECPrivKey()
if err != nil {
return nil, err
}
// if porTxo's private key has something in it, combine that with derived key
// using the delinearization scheme
if kg.PrivKey != empty {
PrivKeyAddBytes(derivedPrivKey, kg.PrivKey[:])
}
// done, return derived sum
return derivedPrivKey, nil
}
// PrivKeyAddBytes adds bytes to a private key.
// NOTE that this modifies the key in place, overwriting it!!!!1
// If k is nil, does nothing and doesn't error (k stays nil)
func PrivKeyAddBytes(k *btcec.PrivateKey, b []byte) {
if k == nil {
return
}
// turn arg bytes into a bigint
arg := new(big.Int).SetBytes(b)
// add private key to arg
k.D.Add(k.D, arg)
// mod 2^256ish
k.D.Mod(k.D, btcec.S256().N)
// new key derived from this sum
// D is already modified, need to update the pubkey x and y
k.X, k.Y = btcec.S256().ScalarBaseMult(k.D.Bytes())
return
}