-
Notifications
You must be signed in to change notification settings - Fork 28
/
account.go
99 lines (83 loc) · 2.44 KB
/
account.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
package main
import (
"context"
"crypto/rand"
"encoding/binary"
"errors"
"github.com/libsv/go-bk/bip32"
"github.com/libsv/go-bk/chaincfg"
"github.com/libsv/go-bt/v2"
"github.com/libsv/go-bt/v2/bscript"
"github.com/libsv/go-bt/v2/unlocker"
)
// account for creating destination scripts and stores these scripts with their derivations.
type account struct {
// masterPrivKey of which all locking scripts and private keys are generated from.
masterPrivKey *bip32.ExtendedKey
// counter for deriving paths for public/private keys
counter uint64
// scriptToPathMap for mapping a locking script hex to its derivation path.
scriptToPathMap map[string]string
}
func newAccount() *account {
// Generate the master private key.
seed, err := bip32.GenerateSeed(bip32.RecommendedSeedLen)
if err != nil {
panic(err)
}
privKey, err := bip32.NewMaster(seed, &chaincfg.MainNet)
if err != nil {
panic(err)
}
return &account{
masterPrivKey: privKey,
scriptToPathMap: make(map[string]string, 0),
}
}
func (a *account) createDestination() *bscript.Script {
// generate a new path until and increment the counter.
path := bip32.DerivePath(a.counter)
a.counter++
// Derive a public key from the new derivation path.
pubKey, err := a.masterPrivKey.DerivePublicKeyFromPath(path)
if err != nil {
panic(err)
}
// Create a locking script from this public key.
s, err := bscript.NewP2PKHFromPubKeyBytes(pubKey)
if err != nil {
panic(err)
}
// Store the locking script and its path for later use.
a.scriptToPathMap[s.String()] = path
return s
}
// Unlocker get the correct unlocker for a given locking script.
func (a *account) Unlocker(ctx context.Context, lockingScript *bscript.Script) (bt.Unlocker, error) {
// Retrieve the path for the given locking script.
path, ok := a.scriptToPathMap[lockingScript.String()]
if !ok {
panic(errors.New("oh no"))
}
// Derive a private key from the stored derivation path. This private key will be pair to
// the public key we derived when this locking script was created.
extPrivKey, err := a.masterPrivKey.DeriveChildFromPath(path)
if err != nil {
panic(err)
}
// Convert the extended key into an eliptic curve private key.
privKey, err := extPrivKey.ECPrivKey()
if err != nil {
panic(err)
}
return &unlocker.Simple{
PrivateKey: privKey,
}, nil
}
func randUint64() uint64 {
var bb [8]byte
if _, err := rand.Read(bb[:]); err != nil {
panic(err)
}
return binary.LittleEndian.Uint64(bb[:])
}