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.

284 lines
14 KiB

  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 int `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 int `meddler:"total_items"`
  43. FirstItem int `meddler:"first_item"`
  44. LastItem int `meddler:"last_item"`
  45. TokenID common.TokenID `meddler:"token_id"`
  46. TokenItemID int `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. AmountFloat float64 `meddler:"amount_f"`
  118. TokenID common.TokenID `meddler:"token_id"`
  119. BatchNum *common.BatchNum `meddler:"batch_num"` // batchNum in which this tx was forged. If the tx is L2, this must be != 0
  120. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
  121. // L1
  122. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
  123. 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
  124. FromEthAddr *ethCommon.Address `meddler:"from_eth_addr"`
  125. FromBJJ *babyjub.PublicKey `meddler:"from_bjj"`
  126. LoadAmount *big.Int `meddler:"load_amount,bigintnull"`
  127. LoadAmountFloat *float64 `meddler:"load_amount_f"`
  128. // L2
  129. Fee *common.FeeSelector `meddler:"fee"`
  130. Nonce *common.Nonce `meddler:"nonce"`
  131. }
  132. // TokenWithUSD add USD info to common.Token
  133. type TokenWithUSD struct {
  134. ItemID int `json:"itemId" meddler:"item_id"`
  135. TokenID common.TokenID `json:"id" meddler:"token_id"`
  136. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"` // Ethereum block number in which this token was registered
  137. EthAddr ethCommon.Address `json:"ethereumAddress" meddler:"eth_addr"`
  138. Name string `json:"name" meddler:"name"`
  139. Symbol string `json:"symbol" meddler:"symbol"`
  140. Decimals uint64 `json:"decimals" meddler:"decimals"`
  141. USD *float64 `json:"USD" meddler:"usd"`
  142. USDUpdate *time.Time `json:"fiatUpdate" meddler:"usd_update,utctime"`
  143. TotalItems int `json:"-" meddler:"total_items"`
  144. FirstItem int `json:"-" meddler:"first_item"`
  145. LastItem int `json:"-" meddler:"last_item"`
  146. }
  147. // ExitAPI is a representation of a exit with additional information
  148. // required by the API, and extracted by joining token table
  149. type ExitAPI struct {
  150. ItemID int `meddler:"item_id"`
  151. BatchNum common.BatchNum `meddler:"batch_num"`
  152. AccountIdx apitypes.HezIdx `meddler:"account_idx"`
  153. MerkleProof *merkletree.CircomVerifierProof `meddler:"merkle_proof,json"`
  154. Balance apitypes.BigIntStr `meddler:"balance"`
  155. InstantWithdrawn *int64 `meddler:"instant_withdrawn"`
  156. DelayedWithdrawRequest *int64 `meddler:"delayed_withdraw_request"`
  157. DelayedWithdrawn *int64 `meddler:"delayed_withdrawn"`
  158. TotalItems int `meddler:"total_items"`
  159. FirstItem int `meddler:"first_item"`
  160. LastItem int `meddler:"last_item"`
  161. TokenID common.TokenID `meddler:"token_id"`
  162. TokenItemID int `meddler:"token_item_id"`
  163. TokenEthBlockNum int64 `meddler:"token_block"`
  164. TokenEthAddr ethCommon.Address `meddler:"eth_addr"`
  165. TokenName string `meddler:"name"`
  166. TokenSymbol string `meddler:"symbol"`
  167. TokenDecimals uint64 `meddler:"decimals"`
  168. TokenUSD *float64 `meddler:"usd"`
  169. TokenUSDUpdate *time.Time `meddler:"usd_update"`
  170. }
  171. // MarshalJSON is used to neast some of the fields of ExitAPI
  172. // without the need of auxiliar structs
  173. func (e ExitAPI) MarshalJSON() ([]byte, error) {
  174. siblings := []string{}
  175. for i := 0; i < len(e.MerkleProof.Siblings); i++ {
  176. siblings = append(siblings, e.MerkleProof.Siblings[i].String())
  177. }
  178. return json.Marshal(map[string]interface{}{
  179. "itemId": e.ItemID,
  180. "batchNum": e.BatchNum,
  181. "accountIndex": e.AccountIdx,
  182. "merkleProof": map[string]interface{}{
  183. "Root": e.MerkleProof.Root.String(),
  184. "Siblings": siblings,
  185. "OldKey": e.MerkleProof.OldKey.String(),
  186. "OldValue": e.MerkleProof.OldValue.String(),
  187. "IsOld0": e.MerkleProof.IsOld0,
  188. "Key": e.MerkleProof.Key.String(),
  189. "Value": e.MerkleProof.Value.String(),
  190. "Fnc": e.MerkleProof.Fnc,
  191. },
  192. "balance": e.Balance,
  193. "instantWithdrawn": e.InstantWithdrawn,
  194. "delayedWithdrawRequest": e.DelayedWithdrawRequest,
  195. "delayedWithdrawn": e.DelayedWithdrawn,
  196. "token": map[string]interface{}{
  197. "id": e.TokenID,
  198. "itemId": e.TokenItemID,
  199. "ethereumBlockNum": e.TokenEthBlockNum,
  200. "ethereumAddress": e.TokenEthAddr,
  201. "name": e.TokenName,
  202. "symbol": e.TokenSymbol,
  203. "decimals": e.TokenDecimals,
  204. "USD": e.TokenUSD,
  205. "fiatUpdate": e.TokenUSDUpdate,
  206. },
  207. })
  208. }
  209. // CoordinatorAPI is a representation of a coordinator with additional information
  210. // required by the API
  211. type CoordinatorAPI struct {
  212. ItemID int `json:"itemId" meddler:"item_id"`
  213. Bidder ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
  214. Forger ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  215. EthBlockNum int64 `json:"ethereumBlock" meddler:"eth_block_num"`
  216. URL string `json:"URL" meddler:"url"`
  217. TotalItems int `json:"-" meddler:"total_items"`
  218. FirstItem int `json:"-" meddler:"first_item"`
  219. LastItem int `json:"-" meddler:"last_item"`
  220. }
  221. // BatchAPI is a representation of a batch with additional information
  222. // required by the API, and extracted by joining block table
  223. type BatchAPI struct {
  224. ItemID int `json:"itemId" meddler:"item_id"`
  225. BatchNum common.BatchNum `json:"batchNum" meddler:"batch_num"`
  226. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  227. EthBlockHash ethCommon.Hash `json:"ethereumBlockHash" meddler:"hash"`
  228. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  229. ForgerAddr ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  230. CollectedFees apitypes.CollectedFees `json:"collectedFees" meddler:"fees_collected,json"`
  231. TotalFeesUSD *float64 `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
  232. StateRoot apitypes.BigIntStr `json:"stateRoot" meddler:"state_root"`
  233. NumAccounts int `json:"numAccounts" meddler:"num_accounts"`
  234. ExitRoot apitypes.BigIntStr `json:"exitRoot" meddler:"exit_root"`
  235. ForgeL1TxsNum *int64 `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
  236. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  237. TotalItems int `json:"-" meddler:"total_items"`
  238. FirstItem int `json:"-" meddler:"first_item"`
  239. LastItem int `json:"-" meddler:"last_item"`
  240. }
  241. // Network define status of the network
  242. type Network struct {
  243. LastBlock int64 `json:"lastBlock"`
  244. LastBatch BatchAPI `json:"lastBatch"`
  245. CurrentSlot int64 `json:"currentSlot"`
  246. NextForgers []CoordinatorAPI `json:"nextForgers"`
  247. }
  248. // Metrics define metrics of the network
  249. type Metrics struct {
  250. TransactionsPerBatch float64 `json:"transactionsPerBatch"`
  251. BatchFrequency float64 `json:"batchFrequency"`
  252. TransactionsPerSecond float64 `json:"transactionsPerSecond"`
  253. TotalAccounts int64 `json:"totalAccounts"`
  254. TotalBJJs int64 `json:"totalBJJs"`
  255. AvgTransactionFee float64 `json:"avgTransactionFee"`
  256. }
  257. // BidAPI is a representation of a bid with additional information
  258. // required by the API
  259. type BidAPI struct {
  260. ItemID int `json:"itemId" meddler:"item_id"`
  261. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  262. BidValue apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
  263. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  264. Bidder ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
  265. Forger ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  266. URL string `json:"URL" meddler:"url"`
  267. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  268. TotalItems int `json:"-" meddler:"total_items"`
  269. FirstItem int `json:"-" meddler:"first_item"`
  270. LastItem int `json:"-" meddler:"last_item"`
  271. }