-
Notifications
You must be signed in to change notification settings - Fork 22
/
admin_check_transaction.go
275 lines (233 loc) · 9.1 KB
/
admin_check_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"
"code.vegaprotocol.io/vega/wallet/api/node"
wcommands "code.vegaprotocol.io/vega/wallet/commands"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/mitchellh/mapstructure"
)
type AdminCheckTransactionParams struct {
Wallet string `json:"wallet"`
PublicKey string `json:"publicKey"`
Network string `json:"network"`
NodeAddress string `json:"nodeAddress"`
Retries uint64 `json:"retries"`
MaximumRequestDuration time.Duration `json:"maximumRequestDuration"`
Transaction interface{} `json:"transaction"`
}
type ParsedAdminCheckTransactionParams struct {
Wallet string
PublicKey string
Network string
NodeAddress string
Retries uint64
RawTransaction string
MaximumRequestDuration time.Duration
}
type AdminCheckTransactionResult struct {
ReceivedAt time.Time `json:"receivedAt"`
SentAt time.Time `json:"sentAt"`
Transaction *commandspb.Transaction `json:"transaction"`
Node AdminNodeInfoResult `json:"node"`
EncodedTransaction string `json:"encodedTransaction"`
}
type AdminCheckTransaction struct {
walletStore WalletStore
networkStore NetworkStore
nodeSelectorBuilder NodeSelectorBuilder
}
func (h *AdminCheckTransaction) Handle(ctx context.Context, rawParams jsonrpc.Params) (jsonrpc.Result, *jsonrpc.ErrorDetails) {
receivedAt := time.Now()
params, err := validateAdminCheckTransactionParams(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)
}
currentNode, errDetails := h.getNode(ctx, params)
if errDetails != nil {
return nil, errDetails
}
lastBlockData, errDetails := h.getLastBlockDataFromNetwork(ctx, currentNode)
if errDetails != nil {
return nil, errDetails
}
marshaledInputData, err := wcommands.ToMarshaledInputData(request, 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, lastBlockData.ChainID))
if err != nil {
return nil, InternalError(fmt.Errorf("could not check 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(lastBlockData.BlockHash, txID, uint(lastBlockData.ProofOfWorkDifficulty), 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,
}
sentAt := time.Now()
if err := currentNode.CheckTransaction(ctx, tx); err != nil {
return nil, NetworkErrorFromTransactionError(err)
}
rawTx, err := proto.Marshal(tx)
if err != nil {
return nil, InternalError(fmt.Errorf("could not marshal the transaction: %w", err))
}
return AdminCheckTransactionResult{
ReceivedAt: receivedAt,
SentAt: sentAt,
Transaction: tx,
Node: AdminNodeInfoResult{
Host: currentNode.Host(),
},
EncodedTransaction: base64.StdEncoding.EncodeToString(rawTx),
}, nil
}
func (h *AdminCheckTransaction) getNode(ctx context.Context, params ParsedAdminCheckTransactionParams) (node.Node, *jsonrpc.ErrorDetails) {
hosts := []string{params.NodeAddress}
if len(params.Network) != 0 {
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)
}
hosts = n.API.GRPC.Hosts
}
nodeSelector, err := h.nodeSelectorBuilder(hosts, params.Retries, params.MaximumRequestDuration)
if err != nil {
return nil, InternalError(fmt.Errorf("could not initialize the node selector: %w", err))
}
currentNode, err := nodeSelector.Node(ctx, noNodeSelectionReporting)
if err != nil {
return nil, NodeCommunicationError(ErrNoHealthyNodeAvailable)
}
return currentNode, nil
}
func (h *AdminCheckTransaction) getLastBlockDataFromNetwork(ctx context.Context, node node.Node) (*AdminLastBlockData, *jsonrpc.ErrorDetails) {
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 NewAdminCheckTransaction(
walletStore WalletStore, networkStore NetworkStore, nodeSelectorBuilder NodeSelectorBuilder,
) *AdminCheckTransaction {
return &AdminCheckTransaction{
walletStore: walletStore,
networkStore: networkStore,
nodeSelectorBuilder: nodeSelectorBuilder,
}
}
func validateAdminCheckTransactionParams(rawParams jsonrpc.Params) (ParsedAdminCheckTransactionParams, error) {
if rawParams == nil {
return ParsedAdminCheckTransactionParams{}, ErrParamsRequired
}
params := AdminCheckTransactionParams{}
if err := mapstructure.Decode(rawParams, ¶ms); err != nil {
return ParsedAdminCheckTransactionParams{}, ErrParamsDoNotMatch
}
if params.Wallet == "" {
return ParsedAdminCheckTransactionParams{}, ErrWalletIsRequired
}
if params.PublicKey == "" {
return ParsedAdminCheckTransactionParams{}, ErrPublicKeyIsRequired
}
if params.Network == "" && params.NodeAddress == "" {
return ParsedAdminCheckTransactionParams{}, ErrNetworkOrNodeAddressIsRequired
}
if params.Network != "" && params.NodeAddress != "" {
return ParsedAdminCheckTransactionParams{}, ErrSpecifyingNetworkAndNodeAddressIsNotSupported
}
if params.Transaction == nil || params.Transaction == "" {
return ParsedAdminCheckTransactionParams{}, ErrTransactionIsRequired
}
tx, err := json.Marshal(params.Transaction)
if err != nil {
return ParsedAdminCheckTransactionParams{}, ErrTransactionIsNotValidJSON
}
return ParsedAdminCheckTransactionParams{
Wallet: params.Wallet,
PublicKey: params.PublicKey,
RawTransaction: string(tx),
Network: params.Network,
NodeAddress: params.NodeAddress,
Retries: params.Retries,
}, nil
}