-
Notifications
You must be signed in to change notification settings - Fork 22
/
client_sign_transaction.go
236 lines (199 loc) · 8.88 KB
/
client_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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"code.vegaprotocol.io/vega/commands"
"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"
)
const TransactionSuccessfullySigned = "The transaction has been successfully signed."
type ClientSignTransactionParams struct {
PublicKey string `json:"publicKey"`
Transaction interface{} `json:"transaction"`
}
type ClientParsedSignTransactionParams struct {
PublicKey string
RawTransaction string
}
type ClientSignTransactionResult struct {
Transaction *commandspb.Transaction `json:"transaction"`
}
type ClientSignTransaction struct {
walletStore WalletStore
interactor Interactor
nodeSelector node.Selector
spam SpamHandler
requestController *RequestController
}
func (h *ClientSignTransaction) Handle(ctx context.Context, rawParams jsonrpc.Params, connectedWallet ConnectedWallet) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
traceID := jsonrpc.TraceIDFromContext(ctx)
receivedAt := time.Now()
params, err := validateSignTransactionParams(rawParams)
if err != nil {
return nil, InvalidParams(err)
}
request := &walletpb.SubmitTransactionRequest{}
if err := jsonpb.Unmarshal(strings.NewReader(params.RawTransaction), request); err != nil {
return nil, InvalidParams(fmt.Errorf("the transaction does not use a valid Vega command: %w", err))
}
if !connectedWallet.CanUseKey(params.PublicKey) {
return nil, RequestNotPermittedError(ErrPublicKeyIsNotAllowedToBeUsed)
}
w, err := h.walletStore.GetWallet(ctx, connectedWallet.Name())
if err != nil {
if errors.Is(err, ErrWalletIsLocked) {
h.interactor.NotifyError(ctx, traceID, ApplicationErrorType, err)
} else {
h.interactor.NotifyError(ctx, traceID, InternalErrorType, fmt.Errorf("could not retrieve the wallet associated to the connection: %w", err))
}
return nil, InternalError(ErrCouldNotSignTransaction)
}
request.PubKey = params.PublicKey
if errs := wcommands.CheckSubmitTransactionRequest(request); !errs.Empty() {
return nil, InvalidParams(errs)
}
iAmDone, err := h.requestController.IsPublicKeyAlreadyInUse(params.PublicKey)
if err != nil {
return nil, RequestNotPermittedError(err)
}
defer iAmDone()
if err := h.interactor.NotifyInteractionSessionBegan(ctx, traceID, TransactionReviewWorkflow, 2); err != nil {
return nil, RequestNotPermittedError(err)
}
defer h.interactor.NotifyInteractionSessionEnded(ctx, traceID)
if connectedWallet.RequireInteraction() {
approved, err := h.interactor.RequestTransactionReviewForSigning(ctx, traceID, 1, connectedWallet.Hostname(), connectedWallet.Name(), params.PublicKey, params.RawTransaction, receivedAt)
if err != nil {
if errDetails := HandleRequestFlowError(ctx, traceID, h.interactor, err); errDetails != nil {
return nil, errDetails
}
h.interactor.NotifyError(ctx, traceID, InternalErrorType, fmt.Errorf("requesting the transaction review failed: %w", err))
return nil, InternalError(ErrCouldNotSignTransaction)
}
if !approved {
return nil, UserRejectionError(ErrUserRejectedSigningOfTransaction)
}
} else {
h.interactor.Log(ctx, traceID, InfoLog, fmt.Sprintf("Trying to sign the transaction: %v", request.String()))
}
h.interactor.Log(ctx, traceID, InfoLog, "Looking for a healthy node...")
currentNode, err := h.nodeSelector.Node(ctx, func(reportType node.ReportType, msg string) {
h.interactor.Log(ctx, traceID, LogType(reportType), msg)
})
if err != nil {
h.interactor.NotifyError(ctx, traceID, NetworkErrorType, fmt.Errorf("could not find a healthy node: %w", err))
return nil, NodeCommunicationError(ErrNoHealthyNodeAvailable)
}
h.interactor.Log(ctx, traceID, InfoLog, "Retrieving latest block information...")
stats, err := currentNode.SpamStatistics(ctx, request.PubKey)
if err != nil {
h.interactor.NotifyError(ctx, traceID, NetworkErrorType, fmt.Errorf("could not get the latest spam statistics for the public key from the node: %w", err))
return nil, NodeCommunicationError(ErrCouldNotGetSpamStatistics)
}
h.interactor.Log(ctx, traceID, SuccessLog, "Latest spam statistics for the public key have been retrieved.")
if stats.LastBlockHeight == 0 {
h.interactor.NotifyError(ctx, traceID, NetworkErrorType, ErrCouldNotGetSpamStatistics)
return nil, NodeCommunicationError(ErrCouldNotGetSpamStatistics)
}
if stats.ChainID == "" {
h.interactor.NotifyError(ctx, traceID, NetworkErrorType, ErrCouldNotGetChainIDFromNode)
return nil, NodeCommunicationError(ErrCouldNotGetChainIDFromNode)
}
h.interactor.Log(ctx, traceID, InfoLog, "Verifying if the transaction passes the anti-spam rules...")
err = h.spam.CheckSubmission(request, &stats)
if err != nil {
h.interactor.NotifyError(ctx, traceID, ApplicationErrorType, fmt.Errorf("could not send transaction: %w", err))
return nil, ApplicationCancellationError(err)
}
h.interactor.Log(ctx, traceID, SuccessLog, "The transaction passes the anti-spam rules.")
// Sign the payload.
inputData, err := wcommands.ToMarshaledInputData(request, stats.LastBlockHeight)
if err != nil {
h.interactor.NotifyError(ctx, traceID, InternalErrorType, fmt.Errorf("could not marshal input data: %w", err))
return nil, InternalError(ErrCouldNotSignTransaction)
}
h.interactor.Log(ctx, traceID, InfoLog, "Signing the transaction...")
signature, err := w.SignTx(params.PublicKey, commands.BundleInputDataForSigning(inputData, stats.ChainID))
if err != nil {
h.interactor.NotifyError(ctx, traceID, InternalErrorType, fmt.Errorf("could not sign the transaction: %w", err))
return nil, InternalError(ErrCouldNotSignTransaction)
}
h.interactor.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.interactor.Log(ctx, traceID, InfoLog, "Computing proof-of-work...")
tx.Pow, err = h.spam.GenerateProofOfWork(params.PublicKey, &stats)
if err != nil {
if errors.Is(err, ErrTransactionsPerBlockLimitReached) || errors.Is(err, ErrBlockHeightTooHistoric) {
h.interactor.NotifyError(ctx, traceID, ApplicationErrorType, fmt.Errorf("could not compute the proof-of-work: %w", err))
return nil, ApplicationCancellationError(err)
}
h.interactor.NotifyError(ctx, traceID, InternalErrorType, fmt.Errorf("could not compute the proof-of-work: %w", err))
return nil, InternalError(ErrCouldNotSignTransaction)
}
h.interactor.Log(ctx, traceID, SuccessLog, "The proof-of-work has been computed.")
h.interactor.NotifySuccessfulRequest(ctx, traceID, 2, TransactionSuccessfullySigned)
return ClientSignTransactionResult{
Transaction: tx,
}, nil
}
func validateSignTransactionParams(rawParams jsonrpc.Params) (ClientParsedSignTransactionParams, error) {
if rawParams == nil {
return ClientParsedSignTransactionParams{}, ErrParamsRequired
}
params := ClientSignTransactionParams{}
if err := mapstructure.Decode(rawParams, ¶ms); err != nil {
return ClientParsedSignTransactionParams{}, ErrParamsDoNotMatch
}
if params.PublicKey == "" {
return ClientParsedSignTransactionParams{}, ErrPublicKeyIsRequired
}
if params.Transaction == nil {
return ClientParsedSignTransactionParams{}, ErrTransactionIsRequired
}
tx, err := json.Marshal(params.Transaction)
if err != nil {
return ClientParsedSignTransactionParams{}, ErrTransactionIsNotValidJSON
}
return ClientParsedSignTransactionParams{
PublicKey: params.PublicKey,
RawTransaction: string(tx),
}, nil
}
func NewClientSignTransaction(walletStore WalletStore, interactor Interactor, nodeSelector node.Selector, proofOfWork SpamHandler, requestController *RequestController) *ClientSignTransaction {
return &ClientSignTransaction{
walletStore: walletStore,
interactor: interactor,
nodeSelector: nodeSelector,
spam: proofOfWork,
requestController: requestController,
}
}