-
Notifications
You must be signed in to change notification settings - Fork 19
/
session_sign_transaction.go
189 lines (159 loc) · 6.31 KB
/
session_sign_transaction.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package api
import (
"context"
"encoding/base64"
"fmt"
"strings"
"time"
"code.vegaprotocol.io/vega/commands"
vgcrypto "code.vegaprotocol.io/vega/libs/crypto"
"code.vegaprotocol.io/vega/libs/jsonrpc"
commandspb "code.vegaprotocol.io/vega/protos/vega/commands/v1"
walletpb "code.vegaprotocol.io/vega/protos/vega/wallet/v1"
"code.vegaprotocol.io/vega/wallet/api/node"
wcommands "code.vegaprotocol.io/vega/wallet/commands"
"github.com/golang/protobuf/jsonpb"
"github.com/mitchellh/mapstructure"
)
type SignTransactionParams struct {
Token string `json:"token"`
PublicKey string `json:"publicKey"`
EncodedTransaction string `json:"encodedTransaction"`
}
type ParsedSignTransactionParams struct {
Token string
PublicKey string
RawTransaction string
}
type SignTransactionResult struct {
Tx *commandspb.Transaction `json:"transaction"`
}
type SignTransaction struct {
pipeline Pipeline
nodeSelector node.Selector
sessions *Sessions
}
func (h *SignTransaction) Handle(ctx context.Context, rawParams jsonrpc.Params) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
traceID := TraceIDFromContext(ctx)
params, err := validateSignTransactionParams(rawParams)
if err != nil {
return nil, invalidParams(err)
}
connectedWallet, err := h.sessions.GetConnectedWallet(params.Token)
if err != nil {
return nil, invalidParams(err)
}
if !connectedWallet.CanUseKey(params.PublicKey) {
return nil, requestNotPermittedError(ErrPublicKeyIsNotAllowedToBeUsed)
}
request := &walletpb.SubmitTransactionRequest{}
if err := jsonpb.Unmarshal(strings.NewReader(params.RawTransaction), request); err != nil {
return nil, invalidParams(ErrTransactionIsMalformed)
}
request.PubKey = params.PublicKey
if errs := wcommands.CheckSubmitTransactionRequest(request); !errs.Empty() {
return nil, invalidParams(errs)
}
receivedAt := time.Now()
approved, err := h.pipeline.RequestTransactionSigningReview(ctx, traceID, connectedWallet.Hostname, connectedWallet.Wallet.Name(), params.PublicKey, params.RawTransaction, receivedAt)
if err != nil {
if errDetails := handleRequestFlowError(ctx, traceID, h.pipeline, err); errDetails != nil {
return nil, errDetails
}
h.pipeline.NotifyError(ctx, traceID, InternalError, fmt.Errorf("requesting the transaction review failed: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
if !approved {
return nil, userRejectionError()
}
h.pipeline.Log(ctx, traceID, InfoLog, "Looking for a healthy node...")
currentNode, err := h.nodeSelector.Node(ctx, func(reportType node.ReportType, msg string) {
h.pipeline.Log(ctx, traceID, LogType(reportType), msg)
})
if err != nil {
h.pipeline.NotifyError(ctx, traceID, NetworkError, fmt.Errorf("could not find a healthy node: %w", err))
return nil, networkError(ErrNoHealthyNodeAvailable)
}
h.pipeline.Log(ctx, traceID, SuccessLog, "A healthy node has been found.")
h.pipeline.Log(ctx, traceID, InfoLog, "Retrieving latest block information...")
lastBlockData, err := currentNode.LastBlock(ctx)
if err != nil {
h.pipeline.NotifyError(ctx, traceID, NetworkError, fmt.Errorf("could not get the latest block from the node: %w", err))
return nil, networkError(ErrCouldNotGetLastBlockInformation)
}
h.pipeline.Log(ctx, traceID, SuccessLog, "Latest block information has been retrieved.")
if lastBlockData.ChainId == "" {
h.pipeline.NotifyError(ctx, traceID, NetworkError, fmt.Errorf("could not get chainID from node: %w", err))
return nil, networkError(ErrCouldNotGetChainIDFromNode)
}
// Sign the payload.
inputData, err := wcommands.ToMarshaledInputData(request, lastBlockData.Height)
if err != nil {
h.pipeline.NotifyError(ctx, traceID, InternalError, fmt.Errorf("could not marshal input data: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
h.pipeline.Log(ctx, traceID, InfoLog, "Signing the transaction...")
signature, err := connectedWallet.Wallet.SignTx(params.PublicKey, commands.BundleInputDataForSigning(inputData, lastBlockData.ChainId))
if err != nil {
h.pipeline.NotifyError(ctx, traceID, InternalError, fmt.Errorf("could not sign command: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
h.pipeline.Log(ctx, traceID, SuccessLog, "The transaction has been signed.")
// Build the transaction.
tx := commands.NewTransaction(params.PublicKey, inputData, &commandspb.Signature{
Value: signature.Value,
Algo: signature.Algo,
Version: signature.Version,
})
// Generate the proof of work for the transaction.
h.pipeline.Log(ctx, traceID, InfoLog, "Computing proof-of-work...")
txID := vgcrypto.RandomHash()
powNonce, _, err := vgcrypto.PoW(lastBlockData.Hash, txID, uint(lastBlockData.SpamPowDifficulty), lastBlockData.SpamPowHashFunction)
if err != nil {
h.pipeline.NotifyError(ctx, traceID, InternalError, fmt.Errorf("could not compute the proof-of-work: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
tx.Pow = &commandspb.ProofOfWork{
Tid: txID,
Nonce: powNonce,
}
h.pipeline.Log(ctx, traceID, SuccessLog, "The proof-of-work has been computed.")
h.pipeline.NotifySuccessfulRequest(ctx, traceID)
return SignTransactionResult{
Tx: tx,
}, nil
}
func NewSignTransaction(pipeline Pipeline, nodeSelector node.Selector, sessions *Sessions) *SignTransaction {
return &SignTransaction{
pipeline: pipeline,
nodeSelector: nodeSelector,
sessions: sessions,
}
}
func validateSignTransactionParams(rawParams jsonrpc.Params) (ParsedSignTransactionParams, error) {
if rawParams == nil {
return ParsedSignTransactionParams{}, ErrParamsRequired
}
params := SignTransactionParams{}
if err := mapstructure.Decode(rawParams, ¶ms); err != nil {
return ParsedSignTransactionParams{}, ErrParamsDoNotMatch
}
if params.Token == "" {
return ParsedSignTransactionParams{}, ErrConnectionTokenIsRequired
}
if params.PublicKey == "" {
return ParsedSignTransactionParams{}, ErrPublicKeyIsRequired
}
if params.EncodedTransaction == "" {
return ParsedSignTransactionParams{}, ErrEncodedTransactionIsRequired
}
tx, err := base64.StdEncoding.DecodeString(params.EncodedTransaction)
if err != nil {
return ParsedSignTransactionParams{}, ErrEncodedTransactionIsNotValidBase64String
}
return ParsedSignTransactionParams{
Token: params.Token,
PublicKey: params.PublicKey,
RawTransaction: string(tx),
}, nil
}