-
Notifications
You must be signed in to change notification settings - Fork 22
/
admin_sign_transaction.go
275 lines (234 loc) · 9.47 KB
/
admin_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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
// 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/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"
wcommands "code.vegaprotocol.io/vega/wallet/commands"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/mitchellh/mapstructure"
)
type AdminLastBlockData struct {
ChainID string `json:"chainID"`
BlockHeight uint64 `json:"blockHeight"`
BlockHash string `json:"blockHash"`
ProofOfWorkHashFunction string `json:"proofOfWorkHashFunction"`
ProofOfWorkDifficulty uint32 `json:"proofOfWorkDifficulty"`
}
type AdminSignTransactionParams struct {
Wallet string `json:"wallet"`
PublicKey string `json:"publicKey"`
Network string `json:"network"`
Transaction interface{} `json:"transaction"`
Retries uint64 `json:"retries"`
MaximumRequestDuration time.Duration `json:"maximumRequestDuration"`
LastBlockData *AdminLastBlockData `json:"lastBlockData"`
}
type ParsedAdminSignTransactionParams struct {
Wallet string
PublicKey string
RawTransaction string
Network string
Retries uint64
MaximumRequestDuration time.Duration
LastBlockData *AdminLastBlockData
}
type AdminSignTransactionResult struct {
Transaction *commandspb.Transaction `json:"transaction"`
EncodedTransaction string `json:"encodedTransaction"`
}
type AdminSignTransaction struct {
walletStore WalletStore
networkStore NetworkStore
nodeSelectorBuilder NodeSelectorBuilder
}
func (h *AdminSignTransaction) Handle(ctx context.Context, rawParams jsonrpc.Params) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
params, err := validateAdminSignTransactionParams(rawParams)
if err != nil {
return nil, InvalidParams(err)
}
if exist, err := h.walletStore.WalletExists(ctx, params.Wallet); err != nil {
return nil, InternalError(fmt.Errorf("could not verify the wallet exists: %w", err))
} else if !exist {
return nil, InvalidParams(ErrWalletDoesNotExist)
}
alreadyUnlocked, err := h.walletStore.IsWalletAlreadyUnlocked(ctx, params.Wallet)
if err != nil {
return nil, InternalError(fmt.Errorf("could not verify whether the wallet is already unlock or not: %w", err))
}
if !alreadyUnlocked {
return nil, RequestNotPermittedError(ErrWalletIsLocked)
}
w, err := h.walletStore.GetWallet(ctx, params.Wallet)
if err != nil {
return nil, InternalError(fmt.Errorf("could not retrieve the wallet: %w", 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))
}
request.PubKey = params.PublicKey
request.Propagate = true
if errs := wcommands.CheckSubmitTransactionRequest(request); !errs.Empty() {
return nil, InvalidParams(errs)
}
if params.Network != "" {
lastBlockData, errDetails := h.getLastBlockDataFromNetwork(ctx, params)
if errDetails != nil {
return nil, errDetails
}
params.LastBlockData = lastBlockData
}
marshaledInputData, err := wcommands.ToMarshaledInputData(request, params.LastBlockData.BlockHeight)
if err != nil {
return nil, InternalError(fmt.Errorf("could not marshal the input data: %w", err))
}
signature, err := w.SignTx(params.PublicKey, commands.BundleInputDataForSigning(marshaledInputData, params.LastBlockData.ChainID))
if err != nil {
return nil, InternalError(fmt.Errorf("could not sign the transaction: %w", err))
}
// Build the transaction.
tx := commands.NewTransaction(params.PublicKey, marshaledInputData, &commandspb.Signature{
Value: signature.Value,
Algo: signature.Algo,
Version: signature.Version,
})
// Generate the proof of work for the transaction.
txID := vgcrypto.RandomHash()
powNonce, _, err := vgcrypto.PoW(params.LastBlockData.BlockHash, txID, uint(params.LastBlockData.ProofOfWorkDifficulty), params.LastBlockData.ProofOfWorkHashFunction)
if err != nil {
return nil, InternalError(fmt.Errorf("could not compute the proof-of-work: %w", err))
}
tx.Pow = &commandspb.ProofOfWork{
Nonce: powNonce,
Tid: txID,
}
rawTx, err := proto.Marshal(tx)
if err != nil {
return nil, InternalError(fmt.Errorf("could not marshal the transaction: %w", err))
}
return AdminSignTransactionResult{
Transaction: tx,
EncodedTransaction: base64.StdEncoding.EncodeToString(rawTx),
}, nil
}
func (h *AdminSignTransaction) getLastBlockDataFromNetwork(ctx context.Context, params ParsedAdminSignTransactionParams) (*AdminLastBlockData, *jsonrpc.ErrorDetails) {
exists, err := h.networkStore.NetworkExists(params.Network)
if err != nil {
return nil, InternalError(fmt.Errorf("could not determine if the network exists: %w", err))
} else if !exists {
return nil, InvalidParams(ErrNetworkDoesNotExist)
}
n, err := h.networkStore.GetNetwork(params.Network)
if err != nil {
return nil, InternalError(fmt.Errorf("could not retrieve the network configuration: %w", err))
}
if err := n.EnsureCanConnectGRPCNode(); err != nil {
return nil, InvalidParams(ErrNetworkConfigurationDoesNotHaveGRPCNodes)
}
nodeSelector, err := h.nodeSelectorBuilder(n.API.GRPC.Hosts, params.Retries, params.MaximumRequestDuration)
if err != nil {
return nil, InternalError(fmt.Errorf("could not initialize the node selector: %w", err))
}
node, err := nodeSelector.Node(ctx, noNodeSelectionReporting)
if err != nil {
return nil, NodeCommunicationError(ErrNoHealthyNodeAvailable)
}
lastBlock, err := node.LastBlock(ctx)
if err != nil {
return nil, NodeCommunicationError(ErrCouldNotGetLastBlockInformation)
}
if lastBlock.ChainID == "" {
return nil, NodeCommunicationError(ErrCouldNotGetChainIDFromNode)
}
return &AdminLastBlockData{
BlockHash: lastBlock.BlockHash,
ChainID: lastBlock.ChainID,
BlockHeight: lastBlock.BlockHeight,
ProofOfWorkHashFunction: lastBlock.ProofOfWorkHashFunction,
ProofOfWorkDifficulty: lastBlock.ProofOfWorkDifficulty,
}, nil
}
func NewAdminSignTransaction(walletStore WalletStore, networkStore NetworkStore, nodeSelectorBuilder NodeSelectorBuilder) *AdminSignTransaction {
return &AdminSignTransaction{
walletStore: walletStore,
networkStore: networkStore,
nodeSelectorBuilder: nodeSelectorBuilder,
}
}
func validateAdminSignTransactionParams(rawParams jsonrpc.Params) (ParsedAdminSignTransactionParams, error) {
if rawParams == nil {
return ParsedAdminSignTransactionParams{}, ErrParamsRequired
}
params := AdminSignTransactionParams{}
if err := mapstructure.Decode(rawParams, ¶ms); err != nil {
return ParsedAdminSignTransactionParams{}, ErrParamsDoNotMatch
}
if params.Wallet == "" {
return ParsedAdminSignTransactionParams{}, ErrWalletIsRequired
}
if params.PublicKey == "" {
return ParsedAdminSignTransactionParams{}, ErrPublicKeyIsRequired
}
if params.Transaction == nil || params.Transaction == "" {
return ParsedAdminSignTransactionParams{}, ErrTransactionIsRequired
}
tx, err := json.Marshal(params.Transaction)
if err != nil {
return ParsedAdminSignTransactionParams{}, ErrTransactionIsNotValidJSON
}
if params.Network != "" && params.LastBlockData != nil {
return ParsedAdminSignTransactionParams{}, ErrSpecifyingNetworkAndLastBlockDataIsNotSupported
}
if params.Network == "" && params.LastBlockData == nil {
return ParsedAdminSignTransactionParams{}, ErrLastBlockDataOrNetworkIsRequired
}
if params.LastBlockData != nil {
if params.LastBlockData.BlockHeight == 0 {
return ParsedAdminSignTransactionParams{}, ErrBlockHeightIsRequired
}
if params.LastBlockData.ChainID == "" {
return ParsedAdminSignTransactionParams{}, ErrChainIDIsRequired
}
if params.LastBlockData.BlockHash == "" {
return ParsedAdminSignTransactionParams{}, ErrBlockHashIsRequired
}
if params.LastBlockData.ProofOfWorkDifficulty == 0 {
return ParsedAdminSignTransactionParams{}, ErrProofOfWorkDifficultyRequired
}
if params.LastBlockData.ProofOfWorkHashFunction == "" {
return ParsedAdminSignTransactionParams{}, ErrProofOfWorkHashFunctionRequired
}
}
return ParsedAdminSignTransactionParams{
Wallet: params.Wallet,
PublicKey: params.PublicKey,
RawTransaction: string(tx),
Network: params.Network,
Retries: params.Retries,
MaximumRequestDuration: params.MaximumRequestDuration,
LastBlockData: params.LastBlockData,
}, nil
}