-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapi.go
More file actions
402 lines (375 loc) · 11.2 KB
/
Copy pathapi.go
File metadata and controls
402 lines (375 loc) · 11.2 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Package api implements the Rosetta API for Flow.
package api
import (
"context"
"encoding/hex"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/coinbase/rosetta-sdk-go/asserter"
"github.com/coinbase/rosetta-sdk-go/server"
"github.com/coinbase/rosetta-sdk-go/types"
"github.com/onflow/rosetta/access"
"github.com/onflow/rosetta/config"
"github.com/onflow/rosetta/indexdb"
"github.com/onflow/rosetta/log"
"github.com/onflow/rosetta/model"
"github.com/onflow/rosetta/process"
"github.com/onflow/rosetta/script"
"github.com/onflow/rosetta/state"
)
const (
callAccountBalances = "account_balances"
callAccountPublicKeys = "account_public_keys"
callBalanceValidationStatus = "balance_validation_status"
callEcho = "echo"
callFeeValidationStatus = "fee_receiver_validation_status"
callLatestBlock = "latest_block"
callListAccounts = "list_accounts"
callVerifyAddress = "verify_address"
opCreateAccount = "create_account"
opCreateProxyAccount = "create_proxy_account"
opDeployContract = "deploy_contract"
opFee = "fee"
opProxyTransfer = "proxy_transfer"
opProxyTransferInner = "proxy_transfer_inner"
opTransfer = "transfer"
opUpdateContract = "update_contract"
statusFailed = "FAILED"
statusSuccess = "SUCCESS"
)
var (
callMethods = []string{
callAccountBalances,
callAccountPublicKeys,
callBalanceValidationStatus,
callEcho,
callFeeValidationStatus,
callLatestBlock,
callListAccounts,
callVerifyAddress,
}
flowCurrency = &types.Currency{
Decimals: 8,
Symbol: "FLOW",
}
opTypes = []string{
opCreateAccount,
opCreateProxyAccount,
opDeployContract,
opFee,
opProxyTransfer,
opProxyTransferInner,
opTransfer,
opUpdateContract,
}
userTag = []byte("FLOW-V0.0-user\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
)
// Server is the Flow Rosetta API server.
type Server struct {
Chain *config.Chain
ConstructionAccessNodes access.Pool
DataAccessNodes access.Pool
Index *indexdb.Store
Indexer *state.Indexer
Offline bool
Port uint16
feeAddrs map[string]bool
genesis *model.BlockMeta
indexedStateErr *types.Error
mu sync.RWMutex // protects indexedStateErr
networks []*types.NetworkIdentifier
scriptBasicTransfer []byte
scriptComputeFees []byte
scriptCreateAccount []byte
scriptCreateProxyAccount []byte
scriptGetBalances []byte
scriptGetBalancesBasic []byte
scriptGetFeeReceivers []byte
scriptGetProxyNonce []byte
scriptGetProxyPublicKey []byte
scriptProxyTransfer []byte
scriptSetContract []byte
validation *validation
validationMu sync.RWMutex // protects validation
feeValidation *feeValidation
feeValidationMu sync.RWMutex // protects feeValidation
}
// Run initializes the server and starts serving Rosetta API calls.
func (s *Server) Run(ctx context.Context) {
s.compileScripts()
s.validation = &validation{
status: validationNotStarted,
}
s.feeValidation = &feeValidation{
status: validationNotStarted,
}
go s.validateBalances(ctx)
s.feeAddrs = s.Chain.Contracts.FeeAddresses()
go s.validateFeeReceivers(ctx)
s.genesis = s.Index.Genesis()
s.networks = []*types.NetworkIdentifier{{
Blockchain: "flow",
Network: s.Chain.Network,
}}
asserter, err := asserter.NewServer(
opTypes,
true,
s.networks,
callMethods,
false,
"",
)
if err != nil {
log.Fatalf("Failed to instantiate the Rosetta asserter: %w", err)
}
wrapped := Wrapper{s}
router := server.NewRouter(
server.NewAccountAPIController(wrapped, asserter),
server.NewBlockAPIController(wrapped, asserter),
server.NewCallAPIController(wrapped, asserter),
server.NewConstructionAPIController(wrapped, asserter),
server.NewMempoolAPIController(wrapped, asserter),
server.NewNetworkAPIController(wrapped, asserter),
)
srv := &http.Server{
Addr: fmt.Sprintf(":%d", s.Port),
Handler: router,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
}
log.Infof("Starting Rosetta Server on port %d", s.Port)
go func() {
process.SetExitHandler(func() {
log.Infof("Shutting down Rosetta HTTP Server gracefully")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Errorf("Failed to shutdown Rosetta HTTP Server gracefully: %s", err)
}
})
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Rosetta HTTP Server failed: %s", err)
}
}()
}
func (s *Server) compileScripts() {
s.scriptBasicTransfer = script.Compile("basic_transfer", script.BasicTransfer, s.Chain)
s.scriptComputeFees = script.Compile("compute_fees", script.ComputeFees, s.Chain)
s.scriptCreateAccount = script.Compile("create_account", script.CreateAccount, s.Chain)
s.scriptCreateProxyAccount = script.Compile("create_proxy_account", script.CreateProxyAccount, s.Chain)
s.scriptGetBalances = script.Compile("get_balances", script.GetBalances, s.Chain)
s.scriptGetBalancesBasic = script.Compile("get_balances_basic", script.GetBalancesBasic, s.Chain)
s.scriptGetFeeReceivers = script.Compile("get_fee_receivers", script.GetFeeReceivers, s.Chain)
s.scriptGetProxyNonce = script.Compile("get_proxy_nonce", script.GetProxyNonce, s.Chain)
s.scriptGetProxyPublicKey = script.Compile("get_proxy_public_key", script.GetProxyPublicKey, s.Chain)
s.scriptProxyTransfer = script.Compile("proxy_transfer", script.ProxyTransfer, s.Chain)
s.scriptSetContract = script.Compile("set_contract", script.SetContract, s.Chain)
}
func (s *Server) getAccount(addr string) ([]byte, *types.Error) {
if len(addr) != 18 || addr[:2] != "0x" {
return nil, wrapErrorf(
errInvalidAccountAddress,
"api: address %q is not valid",
addr,
)
}
acct, err := hex.DecodeString(addr[2:])
if err != nil {
return nil, wrapErrorf(
errInvalidAccountAddress,
"api: address %q could not be hex decoded: %s",
addr, err,
)
}
return acct, nil
}
func (s *Server) getIndexedStateErr() *types.Error {
s.mu.RLock()
xerr := s.indexedStateErr
s.mu.RUnlock()
return xerr
}
func (s *Server) getValidationStatus() *validation {
s.validationMu.RLock()
defer s.validationMu.RUnlock()
return s.validation
}
func (s *Server) setIndexedStateErr(format string, a ...interface{}) {
msg := fmt.Sprintf(format, a...)
log.Errorf(msg)
xerr := wrapErrorf(errInvalidIndexedState, msg)
s.mu.Lock()
// NOTE(tav): We preserve the very first invalid indexed state error we see.
if s.indexedStateErr == nil {
s.indexedStateErr = xerr
}
s.mu.Unlock()
s.validationMu.Lock()
defer s.validationMu.Unlock()
if s.validation.status == validationFailure {
return
}
s.validation = &validation{
err: msg,
status: validationFailure,
}
}
func (s *Server) getFeeValidationStatus() *feeValidation {
s.feeValidationMu.RLock()
defer s.feeValidationMu.RUnlock()
return s.feeValidation
}
func (s *Server) setFeeValidationRetrying(format string, a ...interface{}) {
msg := fmt.Sprintf(format, a...)
log.Errorf("%s", msg)
s.feeValidationMu.Lock()
defer s.feeValidationMu.Unlock()
// We only track transient errors while we're still waiting for the first
// definitive result. Once we have one, it stays in place until the next
// definitive result replaces it.
if s.feeValidation.status == validationSuccess || s.feeValidation.status == validationFailure {
return
}
s.feeValidation = &feeValidation{
err: msg,
status: validationInProgress,
}
}
func (s *Server) setFeeValidationFailure(onchain []string, missing []string) {
msg := fmt.Sprintf(
"On-chain fee receiver account(s) %s are missing from the configured fee addresses: "+
"fee deposits to them would be misclassified as transfers; add them to .contracts.fee_receivers",
strings.Join(missing, ", "),
)
log.Errorf("%s", msg)
s.feeValidationMu.Lock()
defer s.feeValidationMu.Unlock()
s.feeValidation = &feeValidation{
err: msg,
missing: missing,
onchain: onchain,
status: validationFailure,
}
}
func (s *Server) setFeeValidationSuccess(onchain []string) {
s.feeValidationMu.Lock()
prev := s.feeValidation.status
s.feeValidation = &feeValidation{
onchain: onchain,
status: validationSuccess,
}
s.feeValidationMu.Unlock()
// We only log on transitions so that the periodic re-checks don't flood
// the logs.
if prev != validationSuccess {
log.Infof(
"Validated the configured fee addresses against the on-chain fee receivers: %s",
strings.Join(onchain, ", "),
)
}
}
func (s *Server) setValidationProgress(accounts int, checked int) {
s.validationMu.Lock()
defer s.validationMu.Unlock()
if s.validation.status == validationFailure || s.validation.status == validationSuccess {
return
}
s.validation = &validation{
accounts: accounts,
checked: checked,
status: validationInProgress,
}
}
func (s *Server) setValidationSuccess(accounts int) {
s.validationMu.Lock()
defer s.validationMu.Unlock()
if s.validation.status == validationFailure {
return
}
s.validation = &validation{
accounts: accounts,
status: validationSuccess,
}
}
type accountKey struct {
HashAlgorithm uint32 `json:"hash_algorithm"`
KeyIndex uint32 `json:"key_index"`
PublicKey string `json:"public_key"`
SequenceNumber uint32 `json:"sequence_number"`
SignatureAlgorithm uint32 `json:"signature_algorithm"`
Weight uint32 `json:"weight"`
}
type onchainData struct {
DefaultBalance uint64
IsProxy bool
ProxyBalance uint64
}
type innerTxn struct {
amount uint64
nonce uint64
raw []byte
receiver []byte
sender []byte
}
type transferEvent struct {
Amount string `json:"amount"`
Receiver string `json:"receiver,omitempty"`
Sender string `json:"sender,omitempty"`
Type string `json:"type"`
}
type txnIntent struct {
amount uint64
contractCode string
contractName string
contractUpdate bool
keyMessage string
keyMetadata string
keySignature string
keys []string
inner bool
newKey string
prevKeyIndex uint32
proxy bool
receiver []byte
sender []byte
}
// validationStatus enumerates the states a background validation process can
// be in.
type validationStatus int
const (
validationNotStarted validationStatus = iota
validationInProgress
validationSuccess
validationFailure
)
// String returns the status in the form reported by the /call endpoint.
func (v validationStatus) String() string {
switch v {
case validationNotStarted:
return "not_started"
case validationInProgress:
return "in_progress"
case validationSuccess:
return "success"
case validationFailure:
return "failure"
default:
log.Fatalf("Unsupported validation status %d", int(v))
panic("unreachable code")
}
}
type validation struct {
accounts int
checked int
err string
status validationStatus
}
type feeValidation struct {
err string
missing []string
onchain []string
status validationStatus
}