forked from DeathwingTheBoss/hivego
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblockApi.go
370 lines (332 loc) · 12 KB
/
blockApi.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
package hivego
import (
"encoding/binary"
"encoding/hex"
"encoding/json"
"log"
"time"
)
type getBlockRangeQueryParams struct {
StartingBlockNum int `json:"starting_block_num"`
Count int `json:"count"`
}
type getBlockQueryParams struct {
BlockNum int `json:"block_num"`
}
type getVirtualOpsQueryParams struct {
BlockNum int `json:"block_num"`
OnlyVirtual bool `json:"only_virtual"`
IncludeReversible bool `json:"include_reversible"`
}
const (
failureWaitTime = 2500 * time.Millisecond
retryWaitTime = 1000 * time.Millisecond
)
type Block struct {
BlockNumber int
BlockID string `json:"block_id"`
Previous string `json:"previous"`
Timestamp string `json:"timestamp"`
Witness string `json:"witness"`
TransactionMerkleRoot string `json:"transaction_merkle_root"`
Transactions []Transaction `json:"transactions"`
Extensions []interface{} `json:"extensions"`
SigningKey string `json:"signing_key"`
TransactionIds []string `json:"transaction_ids"`
WitnessSignature string `json:"witness_signature"`
}
type Transaction struct {
Expiration string `json:"expiration"`
Extensions []interface{} `json:"extensions"`
Operations []Operation `json:"operations"`
RefBlockNum uint16 `json:"ref_block_num"`
RefBlockPrefix uint32 `json:"ref_block_prefix"`
Signatures []string `json:"signatures"`
RequiredAuths []string `json:"required_auths,omitempty"`
RequiredPostingAuths []string `json:"required_posting_auths,omitempty"`
}
type Operation struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
}
type VirtualOp struct {
Block int `json:"block"`
Op struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
} `json:"op"`
OpInTrx int `json:"op_in_trx"`
TrxId string `json:"trx_id"`
TrxInBlock int `json:"trx_in_block"`
VirtualOp bool `json:"virtual_op"`
OperationId int `json:"operation_id"`
Timestamp string `json:"timestamp"`
}
type operationTypes struct {
Vote string
Comment string
Transfer string
TransferToVesting string
WithdrawVesting string
LimitOrderCreate string
LimitOrderCancel string
FeedPublish string
Convert string
AccountCreate string
AccountUpdate string
WitnessUpdate string
AccountWitnessVote string
AccountWitnessProxy string
Pow string
Custom string
ReportOverProduction string
DeleteComment string
CustomJson string
CommentOptions string
SetWithdrawVestingRoute string
LimitOrderCreate2 string
ClaimAccount string
CreateClaimedAccount string
RequestAccountRecovery string
RecoverAccount string
ChangeRecoveryAccount string
EscrowTransfer string
EscrowDispute string
EscrowRelease string
Pow2 string
EscrowApprove string
TransferToSavings string
TransferFromSavings string
CancelTransferFromSavings string
CustomBinary string
DeclineVotingRights string
ResetAccount string
SetResetAccount string
ClaimRewardBalance string
DelegateVestingShares string
AccountCreateWithDelegation string
WitnessSetProperties string
AccountUpdate2 string
CreateProposal string
UpdateProposalVotes string
RemoveProposal string
UpdateProposal string
CollateralizedConvert string
RecurrentTransfer string
}
var OperationType = operationTypes{
Vote: "vote_operation",
Comment: "comment_operation",
Transfer: "transfer_operation",
TransferToVesting: "transfer_to_vesting_operation",
WithdrawVesting: "withdraw_vesting_operation",
LimitOrderCreate: "limit_order_create_operation",
LimitOrderCancel: "limit_order_cancel_operation",
FeedPublish: "feed_publish_operation",
Convert: "convert_operation",
AccountCreate: "account_create_operation",
AccountUpdate: "account_update_operation",
WitnessUpdate: "witness_update_operation",
AccountWitnessVote: "account_witness_vote_operation",
AccountWitnessProxy: "account_witness_proxy_operation",
Pow: "pow_operation",
Custom: "custom_operation",
ReportOverProduction: "report_over_production_operation",
DeleteComment: "delete_comment_operation",
CustomJson: "custom_json_operation",
CommentOptions: "comment_options_operation",
SetWithdrawVestingRoute: "set_withdraw_vesting_route_operation",
LimitOrderCreate2: "limit_order_create2_operation",
ClaimAccount: "claim_account_operation",
CreateClaimedAccount: "create_claimed_account_operation",
RequestAccountRecovery: "request_account_recovery_operation",
RecoverAccount: "recover_account_operation",
ChangeRecoveryAccount: "change_recovery_account_operation",
EscrowTransfer: "escrow_transfer_operation",
EscrowDispute: "escrow_dispute_operation",
EscrowRelease: "escrow_release_operation",
Pow2: "pow2_operation",
EscrowApprove: "escrow_approve_operation",
TransferToSavings: "transfer_to_savings_operation",
TransferFromSavings: "transfer_from_savings_operation",
CancelTransferFromSavings: "cancel_transfer_from_savings_operation",
CustomBinary: "custom_binary_operation",
DeclineVotingRights: "decline_voting_rights_operation",
ResetAccount: "reset_account_operation",
SetResetAccount: "set_reset_account_operation",
ClaimRewardBalance: "claim_reward_balance_operation",
DelegateVestingShares: "delegate_vesting_shares_operation",
AccountCreateWithDelegation: "account_create_with_delegation_operation",
WitnessSetProperties: "witness_set_properties_operation",
AccountUpdate2: "account_update2_operation",
CreateProposal: "create_proposal_operation",
UpdateProposalVotes: "update_proposal_votes_operation",
RemoveProposal: "remove_proposal_operation",
UpdateProposal: "update_proposal_operation",
CollateralizedConvert: "collateralized_convert_operation",
RecurrentTransfer: "recurrent_transfer_operation",
}
func (h *HiveRpcNode) GetBlockRange(startBlock int, count int) ([]Block, error) {
return h.fetchBlockInRange(startBlock, count)
}
func (h *HiveRpcNode) GetBlock(blockNum int) (Block, error) {
blocks, err := h.fetchBlock([]getBlockQueryParams{{BlockNum: blockNum}})
if err != nil || len(blocks) == 0 {
return Block{}, err
}
return blocks[0], nil
}
func (h *HiveRpcNode) StreamBlocks() (<-chan Block, error) {
blockChan := make(chan Block)
go func() {
dynProps := hrpcQuery{method: "condenser_api.get_dynamic_global_properties", params: []string{}}
res, err := h.rpcExec(h.address, dynProps)
if err != nil {
log.Fatalf("Failed to fetch dynamic global properties: %v", err)
close(blockChan)
return
}
var props globalProps
err = json.Unmarshal(res, &props)
if err != nil {
log.Fatalf("Failed to unmarshal dynamic global properties: %v", err)
close(blockChan)
return
}
currentBlock := props.HeadBlockNumber
for {
blockData, err := h.GetBlock(currentBlock)
if err != nil {
log.Printf("Error fetching block %d: %v\n. Retrying in 3 seconds...", currentBlock, err)
time.Sleep(failureWaitTime)
continue
}
blockChan <- blockData
currentBlock++
time.Sleep(retryWaitTime)
}
}()
return blockChan, nil
}
func (h *HiveRpcNode) FetchVirtualOps(blockHeight int, onlyVirtual bool, IncludeReversible bool) ([]VirtualOp, error) {
params := getVirtualOpsQueryParams{BlockNum: blockHeight, OnlyVirtual: IncludeReversible, IncludeReversible: IncludeReversible}
query := hrpcQuery{method: "account_history_api.get_ops_in_block", params: params}
queries := []hrpcQuery{query}
endpoint := h.address
res, err := h.rpcExecBatchFast(endpoint, queries)
if err != nil {
return nil, err
}
var virtualOpResponses []struct {
ID int `json:"id"`
JsonRPC string `json:"jsonrpc"`
Result struct {
Ops []struct {
Op struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
// Value interface{} `json:"value"`
} `json:"op"`
Block int `json:"block"`
OpInTrx int `json:"op_in_trx"`
TrxId string `json:"trx_id"`
TrxInBlock int `json:"trx_in_block"`
VirtualOp bool `json:"virtual_op"`
OperationId int `json:"operation_id"`
Timestamp string `json:"timestamp"`
} `json:"ops"`
} `json:"result"`
}
err = json.Unmarshal(res[0], &virtualOpResponses)
if err != nil {
return nil, err
}
var virtualOps []VirtualOp
for _, virtualOpResponse := range virtualOpResponses {
for _, op := range virtualOpResponse.Result.Ops {
virtualOps = append(virtualOps, VirtualOp{
Block: op.Block,
Op: struct {
Type string `json:"type"`
Value map[string]interface{} `json:"value"`
}{
Type: op.Op.Type,
Value: op.Op.Value,
},
OpInTrx: op.OpInTrx,
TrxId: op.TrxId,
TrxInBlock: op.TrxInBlock,
VirtualOp: op.VirtualOp,
OperationId: op.OperationId,
Timestamp: op.Timestamp,
})
}
}
return virtualOps, nil
}
func (h *HiveRpcNode) fetchBlockInRange(startBlock, count int) ([]Block, error) {
params := getBlockRangeQueryParams{StartingBlockNum: startBlock, Count: count}
query := hrpcQuery{method: "block_api.get_block_range", params: params}
queries := []hrpcQuery{query}
endpoint := h.address
res, err := h.rpcExecBatchFast(endpoint, queries)
if err != nil {
return nil, err
}
var blockRangeResponses []struct {
ID int `json:"id"`
JsonRPC string `json:"jsonrpc"`
Result struct {
Blocks []Block `json:"blocks"`
} `json:"result"`
}
err = json.Unmarshal(res[0], &blockRangeResponses)
if err != nil {
return nil, err
}
var blocks []Block
for _, blockRangeResponse := range blockRangeResponses {
blocks = append(blocks, blockRangeResponse.Result.Blocks...)
}
var processedBlocks []Block
for _, block := range blocks {
blockInt, _ := hex.DecodeString(block.BlockID[0:8])
block.BlockNumber = int(binary.BigEndian.Uint32(blockInt))
processedBlocks = append(processedBlocks, block)
}
return processedBlocks, nil
}
func (h *HiveRpcNode) fetchBlock(params []getBlockQueryParams) ([]Block, error) {
var queries []hrpcQuery
for _, param := range params {
query := hrpcQuery{method: "block_api.get_block", params: param}
queries = append(queries, query)
}
endpoint := h.address
res, err := h.rpcExecBatchFast(endpoint, queries)
if err != nil {
return nil, err
}
var blockResponses []struct {
ID int `json:"id"`
JsonRPC string `json:"jsonrpc"`
Result struct {
Block Block `json:"block"`
} `json:"result"`
}
err = json.Unmarshal(res[0], &blockResponses)
if err != nil {
return nil, err
}
var blocks []Block
for _, blockResponse := range blockResponses {
blocks = append(blocks, blockResponse.Result.Block)
}
var processedBlocks []Block
for _, block := range blocks {
blockInt, _ := hex.DecodeString(block.BlockID[0:8])
block.BlockNumber = int(binary.BigEndian.Uint32(blockInt))
processedBlocks = append(processedBlocks, block)
}
return processedBlocks, nil
}