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.

325 lines
16 KiB

4 years ago
4 years ago
4 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. 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 uint64 `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 uint64 `json:"-" meddler:"total_items"`
  144. FirstItem uint64 `json:"-" meddler:"first_item"`
  145. LastItem uint64 `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 uint64 `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 uint64 `meddler:"total_items"`
  159. FirstItem uint64 `meddler:"first_item"`
  160. LastItem uint64 `meddler:"last_item"`
  161. TokenID common.TokenID `meddler:"token_id"`
  162. TokenItemID uint64 `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 uint64 `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 uint64 `json:"-" meddler:"total_items"`
  218. FirstItem uint64 `json:"-" meddler:"first_item"`
  219. LastItem uint64 `json:"-" meddler:"last_item"`
  220. }
  221. // AccountAPI is a representation of a account with additional information
  222. // required by the API
  223. type AccountAPI struct {
  224. ItemID uint64 `meddler:"item_id"`
  225. Idx apitypes.HezIdx `meddler:"idx"`
  226. BatchNum common.BatchNum `meddler:"batch_num"`
  227. PublicKey apitypes.HezBJJ `meddler:"bjj"`
  228. EthAddr apitypes.HezEthAddr `meddler:"eth_addr"`
  229. Nonce common.Nonce `meddler:"-"` // max of 40 bits used
  230. Balance *apitypes.BigIntStr `meddler:"-"` // max of 192 bits used
  231. TotalItems uint64 `meddler:"total_items"`
  232. FirstItem uint64 `meddler:"first_item"`
  233. LastItem uint64 `meddler:"last_item"`
  234. TokenID common.TokenID `meddler:"token_id"`
  235. TokenItemID int `meddler:"token_item_id"`
  236. TokenEthBlockNum int64 `meddler:"token_block"`
  237. TokenEthAddr ethCommon.Address `meddler:"token_eth_addr"`
  238. TokenName string `meddler:"name"`
  239. TokenSymbol string `meddler:"symbol"`
  240. TokenDecimals uint64 `meddler:"decimals"`
  241. TokenUSD *float64 `meddler:"usd"`
  242. TokenUSDUpdate *time.Time `meddler:"usd_update"`
  243. }
  244. // MarshalJSON is used to neast some of the fields of AccountAPI
  245. // without the need of auxiliar structs
  246. func (account AccountAPI) MarshalJSON() ([]byte, error) {
  247. jsonAccount := map[string]interface{}{
  248. "itemId": account.ItemID,
  249. "accountIndex": account.Idx,
  250. "nonce": account.Nonce,
  251. "balance": account.Balance,
  252. "bjj": account.PublicKey,
  253. "hezEthereumAddress": account.EthAddr,
  254. "token": map[string]interface{}{
  255. "id": account.TokenID,
  256. "itemId": account.TokenItemID,
  257. "ethereumBlockNum": account.TokenEthBlockNum,
  258. "ethereumAddress": account.TokenEthAddr,
  259. "name": account.TokenName,
  260. "symbol": account.TokenSymbol,
  261. "decimals": account.TokenDecimals,
  262. "USD": account.TokenUSD,
  263. "fiatUpdate": account.TokenUSDUpdate,
  264. },
  265. }
  266. return json.Marshal(jsonAccount)
  267. }
  268. // BatchAPI is a representation of a batch with additional information
  269. // required by the API, and extracted by joining block table
  270. type BatchAPI struct {
  271. ItemID uint64 `json:"itemId" meddler:"item_id"`
  272. BatchNum common.BatchNum `json:"batchNum" meddler:"batch_num"`
  273. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  274. EthBlockHash ethCommon.Hash `json:"ethereumBlockHash" meddler:"hash"`
  275. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  276. ForgerAddr ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  277. CollectedFees apitypes.CollectedFees `json:"collectedFees" meddler:"fees_collected,json"`
  278. TotalFeesUSD *float64 `json:"historicTotalCollectedFeesUSD" meddler:"total_fees_usd"`
  279. StateRoot apitypes.BigIntStr `json:"stateRoot" meddler:"state_root"`
  280. NumAccounts int `json:"numAccounts" meddler:"num_accounts"`
  281. ExitRoot apitypes.BigIntStr `json:"exitRoot" meddler:"exit_root"`
  282. ForgeL1TxsNum *int64 `json:"forgeL1TransactionsNum" meddler:"forge_l1_txs_num"`
  283. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  284. TotalItems uint64 `json:"-" meddler:"total_items"`
  285. FirstItem uint64 `json:"-" meddler:"first_item"`
  286. LastItem uint64 `json:"-" meddler:"last_item"`
  287. }
  288. // Metrics define metrics of the network
  289. type Metrics struct {
  290. TransactionsPerBatch float64 `json:"transactionsPerBatch"`
  291. BatchFrequency float64 `json:"batchFrequency"`
  292. TransactionsPerSecond float64 `json:"transactionsPerSecond"`
  293. TotalAccounts int64 `json:"totalAccounts"`
  294. TotalBJJs int64 `json:"totalBJJs"`
  295. AvgTransactionFee float64 `json:"avgTransactionFee"`
  296. }
  297. // BidAPI is a representation of a bid with additional information
  298. // required by the API
  299. type BidAPI struct {
  300. ItemID uint64 `json:"itemId" meddler:"item_id"`
  301. SlotNum int64 `json:"slotNum" meddler:"slot_num"`
  302. BidValue apitypes.BigIntStr `json:"bidValue" meddler:"bid_value"`
  303. EthBlockNum int64 `json:"ethereumBlockNum" meddler:"eth_block_num"`
  304. Bidder ethCommon.Address `json:"bidderAddr" meddler:"bidder_addr"`
  305. Forger ethCommon.Address `json:"forgerAddr" meddler:"forger_addr"`
  306. URL string `json:"URL" meddler:"url"`
  307. Timestamp time.Time `json:"timestamp" meddler:"timestamp,utctime"`
  308. TotalItems uint64 `json:"-" meddler:"total_items"`
  309. FirstItem uint64 `json:"-" meddler:"first_item"`
  310. LastItem uint64 `json:"-" meddler:"last_item"`
  311. }