-
Notifications
You must be signed in to change notification settings - Fork 17
/
initializer.go
97 lines (80 loc) · 2.54 KB
/
initializer.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
package main
import (
"errors"
keycard "github.com/status-im/keycard-go"
"github.com/status-im/keycard-go/apdu"
"github.com/status-im/keycard-go/globalplatform"
"github.com/status-im/keycard-go/io"
"github.com/status-im/keycard-go/types"
)
var (
errAppletNotInstalled = errors.New("applet not installed")
errCardNotInitialized = errors.New("card not initialized")
errCardAlreadyInitialized = errors.New("card already initialized")
ErrNotInitialized = errors.New("card not initialized")
ErrNotInstalled = errors.New("applet not initialized")
ErrCashNotInstalled = errors.New("cash applet not initialized")
)
// Initializer defines a struct with methods to install applets and initialize a card.
type Initializer struct {
c types.Channel
}
// NewInitializer returns a new Initializer that communicates to Transmitter t.
func NewInitializer(t io.Transmitter) *Initializer {
return &Initializer{
c: io.NewNormalChannel(t),
}
}
func (i *Initializer) Init() (*keycard.Secrets, error) {
logger.Info("initialization started")
cmdSet := keycard.NewCommandSet(i.c)
secrets, err := keycard.GenerateSecrets()
if err != nil {
return nil, err
}
logger.Info("select keycard applet")
err = cmdSet.Select()
if err != nil {
logger.Error("select failed", "error", err)
return nil, err
}
if !cmdSet.ApplicationInfo.Installed {
logger.Error("initialization failed", "error", errAppletNotInstalled)
return nil, errAppletNotInstalled
}
if cmdSet.ApplicationInfo.Initialized {
logger.Error("initialization failed", "error", errCardAlreadyInitialized)
return nil, errCardAlreadyInitialized
}
logger.Info("initializing")
err = cmdSet.Init(secrets)
if err != nil {
return nil, err
}
return secrets, nil
}
// Info returns a types.ApplicationInfo struct with info about the card.
func (i *Initializer) Info() (*types.ApplicationInfo, *types.CashApplicationInfo, error) {
logger.Info("info started")
cmdSet := keycard.NewCommandSet(i.c)
logger.Info("select keycard applet")
err := cmdSet.Select()
if err != nil {
if e, ok := err.(*apdu.ErrBadResponse); ok && e.Sw == globalplatform.SwFileNotFound {
err = nil
} else {
logger.Error("select failed", "error", err)
}
}
logger.Info("select cash applet")
cashCmdSet := keycard.NewCashCommandSet(i.c)
err = cashCmdSet.Select()
if err != nil {
if e, ok := err.(*apdu.ErrBadResponse); ok && e.Sw == globalplatform.SwFileNotFound {
err = nil
} else {
logger.Error("select failed", "error", err)
}
}
return cmdSet.ApplicationInfo, cashCmdSet.CashApplicationInfo, err
}