You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

336 lines
16 KiB

3 years ago
3 years ago
3 years ago
  1. package historydb
  2. import (
  3. "encoding/json"
  4. "math/big"
  5. "time"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/hermeznetwork/hermez-node/apitypes"
  8. "github.com/hermeznetwork/hermez-node/common"
  9. "github.com/iden3/go-iden3-crypto/babyjub"
  10. "github.com/iden3/go-merkletree"
  11. )
  12. // TxAPI is a representation of a generic Tx with additional information
  13. // required by the API, and extracted by joining block and token tables
  14. type TxAPI struct {
  15. // Generic
  16. IsL1 bool `meddler:"is_l1"`
  17. TxID common.TxID `meddler:"id"`
  18. ItemID uint64 `meddler:"item_id"`
  19. Type common.TxType `meddler:"type"`
  20. Position int `meddler:"position"`
  21. FromIdx *apitypes.HezIdx `meddler:"from_idx"`
  22. FromEthAddr *apitypes.HezEthAddr `meddler:"from_eth_addr"`
  23. FromBJJ *apitypes.HezBJJ `meddler:"from_bjj"`
  24. ToIdx apitypes.HezIdx `meddler:"to_idx"`
  25. ToEthAddr *apitypes.HezEthAddr `meddler:"to_eth_addr"`
  26. ToBJJ *apitypes.HezBJJ `meddler:"to_bjj"`
  27. Amount apitypes.BigIntStr `meddler:"amount"`
  28. HistoricUSD *float64 `meddler:"amount_usd"`
  29. BatchNum *common.BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged. If the tx is L2, this must be != 0
  30. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
  31. // L1
  32. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
  33. UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
  34. LoadAmount *apitypes.BigIntStr `meddler:"load_amount"`
  35. HistoricLoadAmountUSD *float64 `meddler:"load_amount_usd"`
  36. // L2
  37. Fee *common.FeeSelector `meddler:"fee"`
  38. HistoricFeeUSD *float64 `meddler:"fee_usd"`
  39. Nonce *common.Nonce `meddler:"nonce"`
  40. // API extras
  41. Timestamp time.Time `meddler:"timestamp,utctime"`
  42. TotalItems uint64 `meddler:"total_items"`
  43. FirstItem uint64 `meddler:"first_item"`
  44. LastItem uint64 `meddler:"last_item"`
  45. TokenID common.TokenID `meddler:"token_id"`
  46. TokenItemID uint64 `meddler:"token_item_id"`
  47. TokenEthBlockNum int64 `meddler:"token_block"`
  48. TokenEthAddr ethCommon.Address `meddler:"eth_addr"`
  49. TokenName string `meddler:"name"`
  50. TokenSymbol string `meddler:"symbol"`
  51. TokenDecimals uint64 `meddler:"decimals"`
  52. TokenUSD *float64 `meddler:"usd"`
  53. TokenUSDUpdate *time.Time `meddler:"usd_update"`
  54. }
  55. // MarshalJSON is used to neast some of the fields of TxAPI
  56. // without the need of auxiliar structs
  57. func (tx TxAPI) MarshalJSON() ([]byte, error) {
  58. jsonTx := map[string]interface{}{
  59. "id": tx.TxID,
  60. "itemId": tx.ItemID,
  61. "type": tx.Type,
  62. "position": tx.Position,
  63. "fromAccountIndex": tx.FromIdx,
  64. "fromHezEthereumAddress": tx.FromEthAddr,
  65. "fromBJJ": tx.FromBJJ,
  66. "toAccountIndex": tx.ToIdx,
  67. "toHezEthereumAddress": tx.ToEthAddr,
  68. "toBJJ": tx.ToBJJ,
  69. "amount": tx.Amount,
  70. "batchNum": tx.BatchNum,
  71. "historicUSD": tx.HistoricUSD,
  72. "timestamp": tx.Timestamp,
  73. "L1Info": nil,
  74. "L2Info": nil,
  75. "token": map[string]interface{}{
  76. "id": tx.TokenID,
  77. "itemId": tx.TokenItemID,
  78. "ethereumBlockNum": tx.TokenEthBlockNum,
  79. "ethereumAddress": tx.TokenEthAddr,
  80. "name": tx.TokenName,
  81. "symbol": tx.TokenSymbol,
  82. "decimals": tx.TokenDecimals,
  83. "USD": tx.TokenUSD,
  84. "fiatUpdate": tx.TokenUSDUpdate,
  85. },
  86. }
  87. if tx.IsL1 {
  88. jsonTx["L1orL2"] = "L1"
  89. jsonTx["L1Info"] = map[string]interface{}{
  90. "toForgeL1TransactionsNum": tx.ToForgeL1TxsNum,
  91. "userOrigin": tx.UserOrigin,
  92. "loadAmount": tx.LoadAmount,
  93. "historicLoadAmountUSD": tx.HistoricLoadAmountUSD,
  94. "ethereumBlockNum": tx.EthBlockNum,
  95. }
  96. } else {
  97. jsonTx["L1orL2"] = "L2"
  98. jsonTx["L2Info"] = map[string]interface{}{
  99. "fee": tx.Fee,
  100. "historicFeeUSD": tx.HistoricFeeUSD,
  101. "nonce": tx.Nonce,
  102. }
  103. }
  104. return json.Marshal(jsonTx)
  105. }
  106. // txWrite is an representatiion that merges common.L1Tx and common.L2Tx
  107. // in order to perform inserts into tx table
  108. type txWrite struct {
  109. // Generic
  110. IsL1 bool `meddler:"is_l1"`
  111. TxID common.TxID `meddler:"id"`
  112. Type common.TxType `meddler:"type"`
  113. Position int `meddler:"position"`
  114. FromIdx *common.Idx `meddler:"from_idx"`
  115. ToIdx common.Idx `meddler:"to_idx"`
  116. Amount *big.Int `meddler:"amount,bigint"`
  117. EffectiveAmount *big.Int `meddler:"effective_amount,bigintnull"`
  118. AmountFloat float64 `meddler:"amount_f"`
  119. TokenID common.TokenID `meddler:"token_id"`
  120. BatchNum *common.BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged. If the tx is L2, this must be != 0
  121. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
  122. // L1
  123. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
  124. UserOrigin *bool `meddler:"user_origin"` // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
  125. FromEthAddr *ethCommon.Address `meddler:"from_eth_addr"`
  126. FromBJJ *babyjub.PublicKey `meddler:"from_bjj"`
  127. LoadAmount *big.Int `meddler:"load_amount,bigintnull"`
  128. EffectiveLoadAmount *big.Int `meddler:"effective_load_amount,bigintnull"`
  129. LoadAmountFloat *float64 `meddler:"load_amount_f"`
  130. // L2
  131. Fee *common.FeeSelector `meddler:"fee"`
  132. Nonce *common.Nonce `meddler:"nonce"`
  133. }
  134. // TokenWithUSD add USD info to common.Token
  135. type TokenWithUSD struct {
  136. ItemID uint64 `json:"itemId" meddler:"item_id"`
  137. TokenID common.TokenID `json:"id" meddler:"token_id"`
  138. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
  139. EthAddr ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
  140. Name string `json:"name" meddler:"name"`
  141. Symbol string `json:"symbol" meddler:"symbol"`
  142. Decimals uint64 `json:"decimals" meddler:"decimals"`
  143. USD *float64 `json:"USD" meddler:"usd"`
  144. USDUpdate *time.Time `json:"fiatUpdate" meddler:"usd_update,utctime"`
  145. TotalItems uint64 `json:"-" meddler:"total_items"`
  146. FirstItem uint64 `json:"-" meddler:"first_item"`
  147. LastItem uint64 `json:"-" meddler:"last_item"`
  148. }
  149. // ExitAPI is a representation of a exit with additional information
  150. // required by the API, and extracted by joining token table
  151. type ExitAPI struct {
  152. ItemID uint64 `meddler:"item_id"`
  153. BatchNum common.BatchNum `meddler:"batch_num"`
  154. AccountIdx apitypes.HezIdx `meddler:"account_idx"`
  155. MerkleProof *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
  156. Balance apitypes.BigIntStr `meddler:"balance"`
  157. InstantWithdrawn *int64 `meddler:"instant_withdrawn"`
  158. DelayedWithdrawRequest *int64 `meddler:"delayed_withdraw_request"`
  159. DelayedWithdrawn *int64 `meddler:"delayed_withdrawn"`
  160. TotalItems uint64 `meddler:"total_items"`
  161. FirstItem uint64 `meddler:"first_item"`
  162. LastItem uint64 `meddler:"last_item"`
  163. TokenID common.TokenID `meddler:"token_id"`
  164. TokenItemID uint64 `meddler:"token_item_id"`
  165. TokenEthBlockNum int64 `meddler:"token_block"`
  166. TokenEthAddr ethCommon.Address `meddler:"eth_addr"`
  167. TokenName string `meddler:"name"`
  168. TokenSymbol string `meddler:"symbol"`
  169. TokenDecimals uint64 `meddler:"decimals"`
  170. TokenUSD *float64 `meddler:"usd"`
  171. TokenUSDUpdate *time.Time `meddler:"usd_update"`
  172. }
  173. // MarshalJSON is used to neast some of the fields of ExitAPI
  174. // without the need of auxiliar structs
  175. func (e ExitAPI) MarshalJSON() ([]byte, error) {
  176. siblings := []string{}
  177. for i := 0; i < len(e.MerkleProof.Siblings); i++ {
  178. siblings = append(siblings, e.MerkleProof.Siblings[i].String())
  179. }
  180. return json.Marshal(map[string]interface{}{
  181. "itemId": e.ItemID,
  182. "batchNum": e.BatchNum,
  183. "accountIndex": e.AccountIdx,
  184. "merkleProof": map[string]interface{}{
  185. "Root": e.MerkleProof.Root.String(),
  186. "Siblings": siblings,
  187. "OldKey": e.MerkleProof.OldKey.String(),
  188. "OldValue": e.MerkleProof.OldValue.String(),
  189. "IsOld0": e.MerkleProof.IsOld0,
  190. "Key": e.MerkleProof.Key.String(),
  191. "Value": e.MerkleProof.Value.String(),
  192. "Fnc": e.MerkleProof.Fnc,
  193. },
  194. "balance": e.Balance,
  195. "instantWithdrawn": e.InstantWithdrawn,
  196. "delayedWithdrawRequest": e.DelayedWithdrawRequest,
  197. "delayedWithdrawn": e.DelayedWithdrawn,
  198. "token": map[string]interface{}{
  199. "id": e.TokenID,
  200. "itemId": e.TokenItemID,
  201. "ethereumBlockNum": e.TokenEthBlockNum,
  202. "ethereumAddress": e.TokenEthAddr,
  203. "name": e.TokenName,
  204. "symbol": e.TokenSymbol,
  205. "decimals": e.TokenDecimals,
  206. "USD": e.TokenUSD,
  207. "fiatUpdate": e.TokenUSDUpdate,
  208. },
  209. })
  210. }
  211. // CoordinatorAPI is a representation of a coordinator with additional information
  212. // required by the API
  213. type CoordinatorAPI struct {
  214. ItemID uint64 `json:"itemId" meddler:"item_id"`
  215. Bidder ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
  216. Forger ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  217. EthBlockNum int64 `json:"ethereumBlock" meddler:"eth_block_num"`
  218. URL string `json:"URL" meddler:"url"`
  219. TotalItems uint64 `json:"-" meddler:"total_items"`
  220. FirstItem uint64 `json:"-" meddler:"first_item"`
  221. LastItem uint64 `json:"-" meddler:"last_item"`
  222. }
  223. // AccountAPI is a representation of a account with additional information
  224. // required by the API
  225. type AccountAPI struct {
  226. ItemID uint64 `meddler:"item_id"`
  227. Idx apitypes.HezIdx `meddler:"idx"`
  228. BatchNum common.BatchNum `meddler:"batch_num"`
  229. PublicKey apitypes.HezBJJ `meddler:"bjj"`
  230. EthAddr apitypes.HezEthAddr `meddler:"eth_addr"`
  231. Nonce common.Nonce `meddler:"-"` // max of 40 bits used
  232. Balance *apitypes.BigIntStr `meddler:"-"` // max of 192 bits used
  233. TotalItems uint64 `meddler:"total_items"`
  234. FirstItem uint64 `meddler:"first_item"`
  235. LastItem uint64 `meddler:"last_item"`
  236. TokenID common.TokenID `meddler:"token_id"`
  237. TokenItemID int `meddler:"token_item_id"`
  238. TokenEthBlockNum int64 `meddler:"token_block"`
  239. TokenEthAddr ethCommon.Address `meddler:"token_eth_addr"`
  240. TokenName string `meddler:"name"`
  241. TokenSymbol string `meddler:"symbol"`
  242. TokenDecimals uint64 `meddler:"decimals"`
  243. TokenUSD *float64 `meddler:"usd"`
  244. TokenUSDUpdate *time.Time `meddler:"usd_update"`
  245. }
  246. // MarshalJSON is used to neast some of the fields of AccountAPI
  247. // without the need of auxiliar structs
  248. func (account AccountAPI) MarshalJSON() ([]byte, error) {
  249. jsonAccount := map[string]interface{}{
  250. "itemId": account.ItemID,
  251. "accountIndex": account.Idx,
  252. "nonce": account.Nonce,
  253. "balance": account.Balance,
  254. "bjj": account.PublicKey,
  255. "hezEthereumAddress": account.EthAddr,
  256. "token": map[string]interface{}{
  257. "id": account.TokenID,
  258. "itemId": account.TokenItemID,
  259. "ethereumBlockNum": account.TokenEthBlockNum,
  260. "ethereumAddress": account.TokenEthAddr,
  261. "name": account.TokenName,
  262. "symbol": account.TokenSymbol,
  263. "decimals": account.TokenDecimals,
  264. "USD": account.TokenUSD,
  265. "fiatUpdate": account.TokenUSDUpdate,
  266. },
  267. }
  268. return json.Marshal(jsonAccount)
  269. }
  270. // BatchAPI is a representation of a batch with additional information
  271. // required by the API, and extracted by joining block table
  272. type BatchAPI struct {
  273. ItemID uint64 `json:"itemId" meddler:"item_id"`
  274. BatchNum common.BatchNum `json:"batchNum" meddler:"batch_num"`
  275. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  276. EthBlockHash ethCommon.Hash `json:"ethereumBlockHash" meddler:"hash"`
  277. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  278. ForgerAddr ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  279. CollectedFees apitypes.CollectedFees `json:"collectedFees" meddler:"fees_collected,json"`
  280. TotalFeesUSD *float64 `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
  281. StateRoot apitypes.BigIntStr `json:"stateRoot" meddler:"state_root"`
  282. NumAccounts int `json:"numAccounts" meddler:"num_accounts"`
  283. ExitRoot apitypes.BigIntStr `json:"exitRoot" meddler:"exit_root"`
  284. ForgeL1TxsNum *int64 `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
  285. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  286. TotalItems uint64 `json:"-" meddler:"total_items"`
  287. FirstItem uint64 `json:"-" meddler:"first_item"`
  288. LastItem uint64 `json:"-" meddler:"last_item"`
  289. }
  290. // Metrics define metrics of the network
  291. type Metrics struct {
  292. TransactionsPerBatch float64 `json:"transactionsPerBatch"`
  293. BatchFrequency float64 `json:"batchFrequency"`
  294. TransactionsPerSecond float64 `json:"transactionsPerSecond"`
  295. TotalAccounts int64 `json:"totalAccounts" meddler:"total_accounts"`
  296. TotalBJJs int64 `json:"totalBJJs" meddler:"total_bjjs"`
  297. AvgTransactionFee float64 `json:"avgTransactionFee"`
  298. }
  299. // MetricsTotals is used to get temporal information from HistoryDB
  300. // to calculate data to be stored into the Metrics struct
  301. type MetricsTotals struct {
  302. TotalTransactions uint64 `meddler:"total_txs"`
  303. FirstBatchNum common.BatchNum `meddler:"batch_num"`
  304. TotalBatches int64 `meddler:"total_batches"`
  305. TotalFeesUSD float64 `meddler:"total_fees"`
  306. }
  307. // BidAPI is a representation of a bid with additional information
  308. // required by the API
  309. type BidAPI struct {
  310. ItemID uint64 `json:"itemId" meddler:"item_id"`
  311. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  312. BidValue apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
  313. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  314. Bidder ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
  315. Forger ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  316. URL string `json:"URL" meddler:"url"`
  317. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  318. TotalItems uint64 `json:"-" meddler:"total_items"`
  319. FirstItem uint64 `json:"-" meddler:"first_item"`
  320. LastItem uint64 `json:"-" meddler:"last_item"`
  321. }