-
Notifications
You must be signed in to change notification settings - Fork 22
/
client_sign_transaction.go
216 lines (182 loc) · 7.6 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
package api
import (
"context"
"encoding/base64"
"encoding/json"
"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"
"code.vegaprotocol.io/vega/wallet/api/session"
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 {
Token string `json:"token"`
PublicKey string `json:"publicKey"`
EncodedTransaction string `json:"encodedTransaction"`
Transaction interface{} `json:"transaction"`
}
type ClientParsedSignTransactionParams struct {
Token string
PublicKey string
RawTransaction string
}
type ClientSignTransactionResult struct {
Tx *commandspb.Transaction `json:"transaction"`
}
type ClientSignTransaction struct {
interactor Interactor
nodeSelector node.Selector
sessions *session.Sessions
time TimeProvider
}
func (h *ClientSignTransaction) Handle(ctx context.Context, rawParams jsonrpc.Params, metadata jsonrpc.RequestMetadata) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
params, err := validateSignTransactionParams(rawParams)
if err != nil {
return nil, invalidParams(err)
}
connectedWallet, err := h.sessions.GetConnectedWallet(params.Token, h.time.Now())
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)
}
if err := h.interactor.NotifyInteractionSessionBegan(ctx, metadata.TraceID); err != nil {
return nil, internalError(err)
}
defer h.interactor.NotifyInteractionSessionEnded(ctx, metadata.TraceID)
if connectedWallet.RequireInteraction() {
receivedAt := time.Now()
approved, err := h.interactor.RequestTransactionReviewForSigning(ctx, metadata.TraceID, connectedWallet.Hostname, connectedWallet.Wallet.Name(), params.PublicKey, params.RawTransaction, receivedAt)
if err != nil {
if errDetails := handleRequestFlowError(ctx, metadata.TraceID, h.interactor, err); errDetails != nil {
return nil, errDetails
}
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("requesting the transaction review failed: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
if !approved {
return nil, userRejectionError()
}
}
h.interactor.Log(ctx, metadata.TraceID, InfoLog, "Looking for a healthy node...")
currentNode, err := h.nodeSelector.Node(ctx, func(reportType node.ReportType, msg string) {
h.interactor.Log(ctx, metadata.TraceID, LogType(reportType), msg)
})
if err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, NetworkError, fmt.Errorf("could not find a healthy node: %w", err))
return nil, nodeCommunicationError(ErrNoHealthyNodeAvailable)
}
h.interactor.Log(ctx, metadata.TraceID, InfoLog, "Retrieving latest block information...")
lastBlockData, err := currentNode.LastBlock(ctx)
if err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, NetworkError, fmt.Errorf("could not get the latest block from the node: %w", err))
return nil, nodeCommunicationError(ErrCouldNotGetLastBlockInformation)
}
h.interactor.Log(ctx, metadata.TraceID, SuccessLog, "Latest block information has been retrieved.")
if lastBlockData.ChainID == "" {
h.interactor.NotifyError(ctx, metadata.TraceID, NetworkError, ErrCouldNotGetChainIDFromNode)
return nil, nodeCommunicationError(ErrCouldNotGetChainIDFromNode)
}
// Sign the payload.
inputData, err := wcommands.ToMarshaledInputData(request, lastBlockData.BlockHeight)
if err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not marshal input data: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
h.interactor.Log(ctx, metadata.TraceID, InfoLog, "Signing the transaction...")
signature, err := connectedWallet.Wallet.SignTx(params.PublicKey, commands.BundleInputDataForSigning(inputData, lastBlockData.ChainID))
if err != nil {
h.interactor.NotifyError(ctx, metadata.TraceID, InternalError, fmt.Errorf("could not sign command: %w", err))
return nil, internalError(ErrCouldNotSignTransaction)
}
h.interactor.Log(ctx, metadata.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, metadata.TraceID, InfoLog, "Computing proof-of-work...")
txID := vgcrypto.RandomHash()
powNonce, _, err := vgcrypto.PoW(lastBlockData.BlockHash, txID, uint(lastBlockData.ProofOfWorkDifficulty), lastBlockData.ProofOfWorkHashFunction)
if err != nil {
h.interactor.NotifyError(ctx, metadata.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.interactor.Log(ctx, metadata.TraceID, SuccessLog, "The proof-of-work has been computed.")
h.interactor.NotifySuccessfulRequest(ctx, metadata.TraceID, TransactionSuccessfullySigned)
return ClientSignTransactionResult{
Tx: tx,
}, nil
}
func NewSignTransaction(interactor Interactor, nodeSelector node.Selector, sessions *session.Sessions, tp ...TimeProvider) *ClientSignTransaction {
return &ClientSignTransaction{
interactor: interactor,
nodeSelector: nodeSelector,
sessions: sessions,
time: extractTimeProvider(tp...),
}
}
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.Token == "" {
return ClientParsedSignTransactionParams{}, ErrConnectionTokenIsRequired
}
if params.PublicKey == "" {
return ClientParsedSignTransactionParams{}, ErrPublicKeyIsRequired
}
if params.EncodedTransaction == "" && params.Transaction == nil {
return ClientParsedSignTransactionParams{}, ErrTransactionIsRequired
}
if params.EncodedTransaction != "" && params.Transaction != nil {
return ClientParsedSignTransactionParams{}, ErrEncodedTransactionAndTransactionSupplied
}
var tx []byte
var err error
if params.EncodedTransaction != "" {
tx, err = base64.StdEncoding.DecodeString(params.EncodedTransaction)
if err != nil {
return ClientParsedSignTransactionParams{}, ErrEncodedTransactionIsNotValidBase64String
}
}
if params.Transaction != nil {
tx, err = json.Marshal(params.Transaction)
if err != nil {
return ClientParsedSignTransactionParams{}, ErrEncodedTransactionIsNotValid
}
}
return ClientParsedSignTransactionParams{
Token: params.Token,
PublicKey: params.PublicKey,
RawTransaction: string(tx),
}, nil
}