-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathservicer.go
305 lines (253 loc) · 10.1 KB
/
servicer.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package cli
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/spf13/cobra"
"github.com/pokt-network/pocket/app/client/cli/cache"
"github.com/pokt-network/pocket/app/client/cli/flags"
"github.com/pokt-network/pocket/logger"
"github.com/pokt-network/pocket/rpc"
coreTypes "github.com/pokt-network/pocket/shared/core/types"
"github.com/pokt-network/pocket/shared/crypto"
)
// IMPROVE: make this configurable
const sessionCacheDBPath = "/tmp"
var (
errNoSessionCache = errors.New("session cache not set up")
errSessionNotFoundInCache = errors.New("session not found in cache")
errNoMatchingSessionInCache = errors.New("no session matching the requested height found in cache")
sessionCache cache.SessionCache
)
func init() {
rootCmd.AddCommand(NewServicerCommand())
var err error
sessionCache, err = cache.NewSessionCache(sessionCacheDBPath)
if err != nil {
logger.Global.Warn().Err(err).Msg("failed to initialize session cache")
}
}
func NewServicerCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "Servicer",
Short: "Servicer specific commands",
Aliases: []string{"servicer"},
Args: cobra.ExactArgs(0),
}
cmds := servicerCommands()
applySubcommandOptions(cmds, attachPwdFlagToSubcommands())
applySubcommandOptions(cmds, attachKeybaseFlagsToSubcommands())
cmd.AddCommand(cmds...)
return cmd
}
func servicerCommands() []*cobra.Command {
cmdDef := actorCmdDef{"Servicer", coreTypes.ActorType_ACTOR_TYPE_SERVICER}
cmds := []*cobra.Command{
newStakeCmd(cmdDef),
newEditStakeCmd(cmdDef),
newUnstakeCmd(cmdDef),
newUnpauseCmd(cmdDef),
{
// IMPROVE: allow reading the relay payload from a file with the serialized protobuf via [--input_file]
Use: "Relay <applicationAddrHex> <servicerAddrHex> <relayChainID> <relayPayload>",
Short: "Relay <applicationAddrHex> <servicerAddrHex> <relayChainID> <relayPayload>",
Long: `Sends a trustless relay using <relayPayload> as contents, to the specified active <servicerAddrHex> in the the <applicationAddrHex>'s session.
Will prompt the user for the *application* account passphrase`,
Aliases: []string{},
Args: cobra.ExactArgs(4),
RunE: func(cmd *cobra.Command, args []string) error {
defer func() {
if err := sessionCache.Stop(); err != nil {
logger.Global.Warn().Err(err).Msg("failed to stop session cache")
}
}()
applicationAddr := args[0]
servicerAddr := args[1]
chain := args[2]
relayPayload := args[3]
// REFACTOR: decouple the client logic from the CLI
// The client will: send the trustless relay and return the response (using a single function as entrypoint)
// The CLI will:
// 1) extract the required input from the command arguments
// 2) call the client function (with the inputs above) that performs the trustless relay
pk, err := getPrivateKeyFromKeybase(applicationAddr)
if err != nil {
return fmt.Errorf("error getting application's private key: %w", err)
}
// TECHDEBT(#791): cache session data
session, err := getCurrentSession(cmd.Context(), applicationAddr, chain)
if err != nil {
return fmt.Errorf("Error getting current session: %w", err)
}
servicer, err := validateServicer(session, servicerAddr)
if err != nil {
return fmt.Errorf("error getting servicer for the relay: %w", err)
}
relay, err := buildRelay(relayPayload, pk, session, servicer, applicationAddr)
if err != nil {
return fmt.Errorf("error building relay from payload: %w", err)
}
fmt.Printf("sending trustless relay for %s to %s with payload: %s\n", applicationAddr, servicerAddr, relayPayload)
resp, err := sendTrustlessRelay(cmd.Context(), servicer.ServiceUrl, relay)
if err != nil {
return err
}
fmt.Printf("HTTP status code: %d\n", resp.HTTPResponse.StatusCode)
fmt.Println("Response: ", resp.JSON200)
return nil
},
},
}
return cmds
}
// TODO: add a cli command for fetching sessions
// validateServicer returns the servicer specified by the <servicer> argument.
// It validates that the <servicer> is the address of a servicer that is active in the current session.
func validateServicer(session *rpc.Session, servicerAddress string) (*rpc.ProtocolActor, error) {
for i := range session.Servicers {
if session.Servicers[i].Address == servicerAddress {
return &session.Servicers[i], nil
}
}
// ADDTEST: cover with gherkin tests
return nil, fmt.Errorf("Error getting servicer: address %s does not match any servicers in the session %d", servicerAddress, session.SessionNumber)
}
// getSessionFromCache uses the client-side session cache to fetch a session for app+chain combination at the provided height, if one has already been retrieved and cached.
func getSessionFromCache(c cache.SessionCache, appAddress, chain string, height int64) (*rpc.Session, error) {
if c == nil {
return nil, errNoSessionCache
}
session, err := c.Get(appAddress, chain)
if err != nil {
return nil, fmt.Errorf("%w: %s", errSessionNotFoundInCache, err.Error())
}
// verify the cached session matches the provided height
if height >= session.SessionHeight && height < session.SessionHeight+session.NumSessionBlocks {
return session, nil
}
return nil, errNoMatchingSessionInCache
}
func getCurrentSession(ctx context.Context, appAddress, chain string) (*rpc.Session, error) {
// CONSIDERATION: passing 0 as the height value to get the current session seems more optimal than this.
currentHeight, err := getCurrentHeight(ctx)
if err != nil {
return nil, fmt.Errorf("Error getting current session: %w", err)
}
session, err := getSessionFromCache(sessionCache, appAddress, chain, currentHeight)
if err == nil {
return session, nil
}
req := rpc.SessionRequest{
AppAddress: appAddress,
Chain: chain,
// TODO(#697): Geozone
SessionHeight: currentHeight,
}
client, err := rpc.NewClientWithResponses(flags.RemoteCLIURL)
if err != nil {
return nil, fmt.Errorf("Error getting current session for app/chain/height: %s/%s/%d: %w", appAddress, chain, currentHeight, err)
}
resp, err := client.PostV1ClientGetSessionWithResponse(ctx, req)
if err != nil {
return nil, fmt.Errorf("Error getting current session with request %v: %w", req, err)
}
// CLEANUP: move the HTTP response processing code to a separate function to enable reuse.
if resp.HTTPResponse.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error getting current session: Unexpected status code %d for request %v", resp.HTTPResponse.StatusCode, req)
}
if resp.JSON200 == nil {
return nil, fmt.Errorf("Error getting current session: Unexpected response %v", resp)
}
session = resp.JSON200
if sessionCache == nil {
logger.Global.Warn().Msg("session cache not available: cannot cache the retrieved session")
return session, nil
}
if err := sessionCache.Set(session); err != nil {
logger.Global.Warn().Err(err).Msg("failed to store session in cache")
}
return session, nil
}
// REFACTOR: reuse this function in all the query commands
func getCurrentHeight(ctx context.Context) (int64, error) {
client, err := rpc.NewClientWithResponses(flags.RemoteCLIURL)
if err != nil {
return 0, fmt.Errorf("Error getting current height: %w", err)
}
resp, err := client.GetV1QueryHeightWithResponse(ctx)
if err != nil {
return 0, fmt.Errorf("Error getting current height: %w", err)
}
if resp.HTTPResponse.StatusCode != http.StatusOK {
return 0, fmt.Errorf("Error getting current height: Unexpected status code %d", resp.HTTPResponse.StatusCode)
}
if resp.JSON200 == nil {
return 0, fmt.Errorf("Error getting current height: Unexpected response %v", resp)
}
return resp.JSON200.Height, nil
}
// IMPROVE(#823): [K8s][LocalNet] Publish Servicer(s) Host and Port as env. vars in K8s: similar to Validators
// CONSIDERATION: move package-level variables (e.g. RemoteCLIURL) to a cli object and consider storing it in the context
func sendTrustlessRelay(ctx context.Context, servicerUrl string, relay *rpc.RelayRequest) (*rpc.PostV1ClientRelayResponse, error) {
client, err := rpc.NewClientWithResponses(servicerUrl)
if err != nil {
return nil, err
}
return client.PostV1ClientRelayWithResponse(ctx, *relay)
}
func buildRelay(payload string, appPrivateKey crypto.PrivateKey, session *rpc.Session, servicer *rpc.ProtocolActor, appAddr string) (*rpc.RelayRequest, error) {
// TECHDEBT: This is mostly COPIED from pocket-go: we should refactor pocket-go code and import this functionality from there instead.
var relayPayload rpc.Payload
// INCOMPLETE(#803): need to unmarshal into JSONRPC and other supported relay formats once proto-generated custom types are added.
// INCOMPLETE: set Headers for HTTP relays
if err := json.Unmarshal([]byte(payload), &relayPayload); err != nil {
return nil, fmt.Errorf("error unmarshalling relay payload %s: %w", payload, err)
}
relayMeta := rpc.RelayRequestMeta{
BlockHeight: session.SessionHeight,
// TODO: Make Chain Identifier type consistent in Session and Meta use Identifiable for Chain in Session (or string for Chain in Relay Meta)
Chain: rpc.Identifiable{
Id: session.Chain,
},
ServicerPubKey: servicer.PublicKey,
// TODO(#697): Geozone
ApplicationAddress: appAddr,
}
relay := &rpc.RelayRequest{
Payload: relayPayload,
Meta: relayMeta,
}
// TECHDEBT: Evaluate which fields we should and shouldn't marshall when signing the payload
reqBytes, err := json.Marshal(relay)
if err != nil {
return nil, fmt.Errorf("Error marshalling relay request %v: %w", relay, err)
}
hashedReq := crypto.SHA3Hash(reqBytes)
signature, err := appPrivateKey.Sign(hashedReq)
if err != nil {
return relay, fmt.Errorf("Error signing relay: %w", err)
}
relay.Meta.Signature = hex.EncodeToString(signature)
return relay, nil
}
// TECHDEBT: remove use of package-level variables, such as NonInteractive, RemoteCLIURL, pwd, etc.
func getPrivateKeyFromKeybase(address string) (crypto.PrivateKey, error) {
kb, err := keybaseForCLI()
if err != nil {
return nil, err
}
if !flags.NonInteractive {
pwd = readPassphrase(pwd)
}
pk, err := kb.GetPrivKey(address, pwd)
if err != nil {
return nil, err
}
if err := kb.Stop(); err != nil {
return nil, err
}
return pk, nil
}