forked from goat-systems/go-tezos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock.go
519 lines (411 loc) · 13.1 KB
/
block.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
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package gotezos
import (
"fmt"
"strconv"
"strings"
"time"
)
// GetSnapShot takes a cycle number and returns a helper structure describing a snap shot on the tezos network.
func (gt *GoTezos) GetSnapShot(cycle int) (SnapShot, error) {
var snapShotQuery SnapShotQuery
var snap SnapShot
var get string
// Check cache first
if cachedSS, exists := gt.cache.Get(strconv.Itoa(cycle)); exists {
if gt.debug {
gt.logger.Printf("DEBUG: GetSnapShot %d (Cached)\n", cycle)
}
return cachedSS.(SnapShot), nil
}
if gt.debug {
gt.logger.Printf("GetSnapShot %d\n", cycle)
}
currentCycle, err := gt.GetCurrentCycle()
if err != nil {
return snap, err
}
// Sanity
if cycle > currentCycle+gt.Constants.PreservedCycles-1 {
return snap, fmt.Errorf("unable to fetch snapshot for cycle %d; Cycle does not exist", cycle)
}
snap.Cycle = cycle
strCycle := strconv.Itoa(cycle)
if cycle < currentCycle {
block, err := gt.GetBlockAtLevel(cycle*gt.Constants.BlocksPerCycle + 1)
if err != nil {
return snap, err
}
get = "/chains/main/blocks/" + block.Hash + "/context/raw/json/cycle/" + strCycle
} else {
get = "/chains/main/blocks/head/context/raw/json/cycle/" + strCycle
}
resp, err := gt.GetResponse(get, "{}")
if err != nil {
gt.logger.Println("Could not get snap shot: " + err.Error())
return snap, err
}
snapShotQuery, err = snapShotQuery.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not get snap shot: " + err.Error())
return snap, err
}
snap.Number = snapShotQuery.RollSnapShot
snap.AssociatedBlock = ((cycle - gt.Constants.PreservedCycles - 2) * gt.Constants.BlocksPerCycle) + (snapShotQuery.RollSnapShot+1)*256
if snap.AssociatedBlock < 1 {
snap.AssociatedBlock = 1
}
snap.AssociatedHash, _ = gt.GetBlockHashAtLevel(snap.AssociatedBlock)
// Cache for future
// Can be a longer cache since old snapshots don't change
gt.cache.Set(strconv.Itoa(cycle), snap, 10*time.Minute)
return snap, nil
}
// GetAllCurrentSnapShots gets a list of all known snapshots to the network
func (gt *GoTezos) GetAllCurrentSnapShots() ([]SnapShot, error) {
var snapShotArray []SnapShot
currentCycle, err := gt.GetCurrentCycle()
if err != nil {
return snapShotArray, err
}
for i := 7; i <= currentCycle; i++ {
snapShot, err := gt.GetSnapShot(i)
if err != nil {
return snapShotArray, err
}
snapShotArray = append(snapShotArray, snapShot)
}
return snapShotArray, nil
}
// GetChainHead returns the head block from the Tezos RPC.
func (gt *GoTezos) GetChainHead() (Block, error) {
var block Block
// Check cache
if cachedBlock, exists := gt.cache.Get("head"); exists {
if gt.debug {
gt.logger.Println("DEBUG: GetChainHead() (Cached)")
}
return cachedBlock.(Block), nil
}
if gt.debug {
gt.logger.Println("DEBUG: GetChainHead()")
}
resp, err := gt.GetResponse("/chains/main/blocks/head", "{}")
if err != nil {
gt.logger.Println("Could not get /chains/main/blocks/head: " + err.Error())
return block, err
}
block, err = block.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not get block head: " + err.Error())
return block, err
}
// Cache. Not for too long since the head can change every minute
gt.cache.Set("head", block, 10*time.Second)
return block, nil
}
// GetNetworkConstants gets the network constants for the Tezos network the client is using.
func (gt *GoTezos) GetNetworkConstants() (NetworkConstants, error) {
networkConstants := NetworkConstants{}
resp, err := gt.GetResponse("/chains/main/blocks/head/context/constants", "{}")
if err != nil {
gt.logger.Println("Could not get /chains/main/blocks/head/context/constants: " + err.Error())
return networkConstants, err
}
networkConstants, err = networkConstants.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not get network constants: " + err.Error())
return networkConstants, err
}
return networkConstants, nil
}
// GetNetworkVersions gets the network versions of Tezos network the client is using.
func (gt *GoTezos) GetNetworkVersions() ([]NetworkVersion, error) {
networkVersions := make([]NetworkVersion, 0)
resp, err := gt.GetResponse("/network/versions", "{}")
if err != nil {
gt.logger.Println("Could not get /network/versions: " + err.Error())
return networkVersions, err
}
var nvs NetworkVersions
nvs, err = nvs.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not get network version: " + err.Error())
return networkVersions, err
}
// Extract just the network name and append to returning slice
// 'range' operates on a copy of the struct so cannot update-in-place
for _, v := range nvs {
parts := strings.Split(v.Name, "_")
if len(parts) == 3 {
v.Network = parts[1]
}
networkVersions = append(networkVersions, v)
}
return networkVersions, nil
}
// GetBranchProtocol returns the current Tezos protocol hash
func (gt *GoTezos) GetBranchProtocol() (string, error) {
block, err := gt.GetChainHead()
if err != nil {
return "", err
}
return block.Protocol, nil
}
// GetBranchHash returns the current branches hash
func (gt *GoTezos) GetBranchHash() (string, error) {
block, err := gt.GetChainHead()
if err != nil {
return "", err
}
return block.Hash, nil
}
// GetBlockLevelHead returns the level, and the hash, of the head block.
func (gt *GoTezos) GetBlockLevelHead() (int, string, error) {
block, err := gt.GetChainHead()
if err != nil {
return block.Header.Level, block.Hash, err
}
return block.Header.Level, block.Hash, err
}
// GetBlockHashAtLevel returns the hash of a block at a specific level.
func (gt *GoTezos) GetBlockHashAtLevel(level int) (string, error) {
block, err := gt.GetBlockAtLevel(level)
if err != nil {
return "", err
}
return block.Hash, nil
}
// GetBlockAtLevel returns a Block at a specific level
func (gt *GoTezos) GetBlockAtLevel(level int) (Block, error) {
var block Block
// Check cache for block at level
if cachedBlock, exists := gt.cache.Get(strconv.Itoa(level)); exists {
if gt.debug {
gt.logger.Printf("DEBUG: GetBlockAtLevel %d (Cached)\n", level)
}
return cachedBlock.(Block), nil
}
// Get current head block
headLevel, headHash, err := gt.GetBlockLevelHead()
if err != nil {
return block, err
}
if gt.debug {
gt.logger.Printf("DEBUG: GetBlockAtLevel %d\n", level)
}
diffStr := strconv.Itoa(headLevel - level)
getBlockByLevel := "/chains/main/blocks/" + headHash + "~" + diffStr
if gt.debug {
gt.logger.Printf("DEBUG: - %s\n", getBlockByLevel)
}
resp, err := gt.GetResponse(getBlockByLevel, "{}")
if err != nil {
return block, err
}
block, err = block.UnmarshalJSON(resp.Bytes)
if err != nil {
return block, err
}
// Cache for future
// Can be a longer cache since old blocks don't change
gt.cache.Set(strconv.Itoa(level), block, 10*time.Minute)
return block, nil
}
// GetBlockByHash returns a Block by the identifier hash.
func (gt *GoTezos) GetBlockByHash(hash string) (Block, error) {
var block Block
hashPrefix := hash[:15]
// Check cache
if cachedBlock, exists := gt.cache.Get(hashPrefix); exists {
if gt.debug {
gt.logger.Println("DEBUG: GetBlockByHash (Cached)")
}
return cachedBlock.(Block), nil
}
if gt.debug {
gt.logger.Println("DEBUG: GetBlockByHash")
}
getBlockByLevel := "/chains/main/blocks/" + hash
resp, err := gt.GetResponse(getBlockByLevel, "{}")
if err != nil {
return block, err
}
block, err = block.UnmarshalJSON(resp.Bytes)
if err != nil {
return block, err
}
// Cache for future
// Can be a longer cache since old blocks don't change
gt.cache.Set(hashPrefix, block, 10*time.Minute)
return block, nil
}
// GetBlockOperationHashesHead returns list of operations in the head block
func (gt *GoTezos) GetBlockOperationHashesHead() (OperationHashes, error) {
var operations OperationHashes
// Get head hash
blockHash, err := gt.GetBranchHash()
if err != nil {
gt.logger.Printf("Could not get block hash at head: %s\n", err)
return operations, err
}
// Pass hash to helper
return gt.GetBlockOperationHashes(blockHash)
}
// GetBlockOperationHashesAtLevel returns list of operations in block at specific level
func (gt *GoTezos) GetBlockOperationHashesAtLevel(level int) (OperationHashes, error) {
var operations OperationHashes
blockHash, err := gt.GetBlockHashAtLevel(level)
if err != nil {
gt.logger.Printf("Could not get block hash at level %d: %s\n", level, err)
return operations, err
}
// Pass hash to helper
return gt.GetBlockOperationHashes(blockHash)
}
// GetBlockOperationHashes returns all the operation hashes at specific block hash
func (gt *GoTezos) GetBlockOperationHashes(blockHash string) (OperationHashes, error) {
var operations OperationHashes
resp, err := gt.GetResponse("/chains/main/blocks/"+blockHash+"/operation_hashes", "{}")
if err != nil {
gt.logger.Println("Could not get block operation_hashes: " + err.Error())
return operations, err
}
operations, err = operations.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not decode operation hashes: " + err.Error())
return operations, err
}
return operations, nil
}
// GetBlockRawOperationHashes returns all the operation hashes at specific block hash as returned by RPC method
func (gt *GoTezos) GetBlockRawOperationHashes(blockHash string) (RawOperationHashes, error) {
var operations RawOperationHashes
resp, err := gt.GetResponse("/chains/main/blocks/"+blockHash+"/operation_hashes", "{}")
if err != nil {
gt.logger.Println("Could not get block operation_hashes: " + err.Error())
return operations, err
}
operations, err = operations.UnmarshalJSON(resp.Bytes)
if err != nil {
gt.logger.Println("Could not decode operation hashes: " + err.Error())
return operations, err
}
return operations, nil
}
// GetAccountBalanceAtSnapshot gets the balance of a public key hash at a specific snapshot for a cycle.
func (gt *GoTezos) GetAccountBalanceAtSnapshot(tezosAddr string, cycle int) (float64, error) {
snapShot, err := gt.GetSnapShot(cycle)
if err != nil {
return 0, err
}
hash, err := gt.GetBlockHashAtLevel(snapShot.AssociatedBlock)
if err != nil {
return 0, err
}
balanceCmdStr := "/chains/main/blocks/" + hash + "/context/contracts/" + tezosAddr + "/balance"
resp, err := gt.GetResponse(balanceCmdStr, "{}")
if err != nil {
return 0, err
}
strBalance, err := unmarshalString(resp.Bytes)
if err != nil {
return 0, err
}
floatBalance, err := strconv.ParseFloat(strBalance, 64)
if err != nil {
return 0, err
}
return floatBalance / MUTEZ, nil
}
// GetAccountBalance gets the balance of a public key hash at a specific snapshot for a cycle.
func (gt *GoTezos) GetAccountBalance(tezosAddr string) (float64, error) {
balanceCmdStr := "/chains/main/blocks/head/context/contracts/" + tezosAddr + "/balance"
resp, err := gt.GetResponse(balanceCmdStr, "{}")
if err != nil {
return 0, err
}
strBalance, err := unmarshalString(resp.Bytes)
if err != nil {
return 0, err
}
floatBalance, err := strconv.ParseFloat(strBalance, 64)
if err != nil {
return 0, err
}
return floatBalance / MUTEZ, nil
}
// GetDelegateStakingBalance gets the staking balance for a delegate at a specific snapshot for a cycle.
func (gt *GoTezos) GetDelegateStakingBalance(delegateAddr string, cycle int) (float64, error) {
var snapShot SnapShot
var err error
var hash string
snapShot, err = gt.GetSnapShot(cycle)
if err != nil {
return 0, err
}
hash, err = gt.GetBlockHashAtLevel(snapShot.AssociatedBlock)
if err != nil {
return 0, err
}
rpcCall := "/chains/main/blocks/" + hash + "/context/delegates/" + delegateAddr + "/staking_balance"
resp, err := gt.GetResponse(rpcCall, "{}")
if err != nil {
return 0, err
}
strBalance, err := unmarshalString(resp.Bytes)
if err != nil {
return 0, err
}
floatBalance, err := strconv.ParseFloat(strBalance, 64) //TODO error checking
if err != nil {
return 0, err
}
return floatBalance / MUTEZ, nil
}
// GetCurrentCycle gets the current cycle of the chain
func (gt *GoTezos) GetCurrentCycle() (int, error) {
block, err := gt.GetChainHead()
if err != nil {
return 0, err
}
var cycle int
cycle = block.Metadata.Level.Cycle
return cycle, nil
}
// GetAccountBalanceAtBlock get the balance of an address at a specific hash
func (gt *GoTezos) GetAccountBalanceAtBlock(tezosAddr string, hash string) (int, error) {
var balance string
balanceCmdStr := "/chains/main/blocks/" + hash + "/context/contracts/" + tezosAddr + "/balance"
resp, err := gt.GetResponse(balanceCmdStr, "{}")
if err != nil {
return 0, err
}
balance, err = unmarshalString(resp.Bytes)
if err != nil {
return 0, err
}
var returnBalance int
if strings.Contains(balance, "No service found at gt URL") {
returnBalance = 0
}
if len(balance) < 1 {
returnBalance = 0
} else {
floatBalance, _ := strconv.Atoi(balance) //TODO error checking
returnBalance = int(floatBalance)
}
return returnBalance, nil
}
// GetChainID gets the id of the chain with the most fitness
func (gt *GoTezos) GetChainID() (string, error) {
get := "/chains/main/chain_id"
resp, err := gt.GetResponse(get, "{}")
if err != nil {
return "", err
}
chainID, err := unmarshalString(resp.Bytes)
if err != nil {
return "", err
}
return chainID, nil
}