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.

455 lines
12 KiB

Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
Redo coordinator structure, connect API to node - API: - Modify the constructor so that hardcoded rollup constants don't need to be passed (introduce a `Config` and use `configAPI` internally) - Common: - Update rollup constants with proper *big.Int when required - Add BidCoordinator and Slot structs used by the HistoryDB and Synchronizer. - Add helper methods to AuctionConstants - AuctionVariables: Add column `DefaultSlotSetBidSlotNum` (in the SQL table: `default_slot_set_bid_slot_num`), which indicates at which slotNum does the `DefaultSlotSetBid` specified starts applying. - Config: - Move coordinator exclusive configuration from the node config to the coordinator config - Coordinator: - Reorganize the code towards having the goroutines started and stopped from the coordinator itself instead of the node. - Remove all stop and stopped channels, and use context.Context and sync.WaitGroup instead. - Remove BatchInfo setters and assing variables directly - In ServerProof and ServerProofPool use context instead stop channel. - Use message passing to notify the coordinator about sync updates and reorgs - Introduce the Pipeline, which can be started and stopped by the Coordinator - Introduce the TxManager, which manages ethereum transactions (the TxManager is also in charge of making the forge call to the rollup smart contract). The TxManager keeps ethereum transactions and: 1. Waits for the transaction to be accepted 2. Waits for the transaction to be confirmed for N blocks - In forge logic, first prepare a batch and then wait for an available server proof to have all work ready once the proof server is ready. - Remove the `isForgeSequence` method which was querying the smart contract, and instead use notifications sent by the Synchronizer to figure out if it's forging time. - Update test (which is a minimal test to manually see if the coordinator starts) - HistoryDB: - Add method to get the number of batches in a slot (used to detect when a slot has passed the bid winner forging deadline) - Add method to get the best bid and associated coordinator of a slot (used to detect the forgerAddress that can forge the slot) - General: - Rename some instances of `currentBlock` to `lastBlock` to be more clear. - Node: - Connect the API to the node and call the methods to update cached state when the sync advances blocks. - Call methods to update Coordinator state when the sync advances blocks and finds reorgs. - Synchronizer: - Add Auction field in the Stats, which contain the current slot with info about highest bidder and other related info required to know who can forge in the current block. - Better organization of cached state: - On Sync, update the internal cached state - On Init or Reorg, load the state from HistoryDB into the internal cached state.
4 years ago
  1. package api
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. ethCommon "github.com/ethereum/go-ethereum/common"
  9. "github.com/hermeznetwork/hermez-node/common"
  10. "github.com/hermeznetwork/hermez-node/db/historydb"
  11. "github.com/hermeznetwork/tracerr"
  12. "github.com/iden3/go-iden3-crypto/babyjub"
  13. )
  14. // Query parsers
  15. type querier interface {
  16. Query(string) string
  17. }
  18. func parsePagination(c querier) (fromItem *uint, order string, limit *uint, err error) {
  19. // FromItem
  20. fromItem, err = parseQueryUint("fromItem", nil, 0, maxUint32, c)
  21. if err != nil {
  22. return nil, "", nil, tracerr.Wrap(err)
  23. }
  24. // Order
  25. order = dfltOrder
  26. const orderName = "order"
  27. orderStr := c.Query(orderName)
  28. if orderStr != "" && !(orderStr == historydb.OrderAsc || historydb.OrderDesc == orderStr) {
  29. return nil, "", nil, tracerr.Wrap(errors.New(
  30. "order must have the value " + historydb.OrderAsc + " or " + historydb.OrderDesc,
  31. ))
  32. }
  33. if orderStr == historydb.OrderAsc {
  34. order = historydb.OrderAsc
  35. } else if orderStr == historydb.OrderDesc {
  36. order = historydb.OrderDesc
  37. }
  38. // Limit
  39. limit = new(uint)
  40. *limit = dfltLimit
  41. limit, err = parseQueryUint("limit", limit, 1, maxLimit, c)
  42. if err != nil {
  43. return nil, "", nil, tracerr.Wrap(err)
  44. }
  45. return fromItem, order, limit, nil
  46. }
  47. // nolint reason: res may be not overwriten
  48. func parseQueryUint(name string, dflt *uint, min, max uint, c querier) (*uint, error) { //nolint:SA4009
  49. str := c.Query(name)
  50. return stringToUint(str, name, dflt, min, max)
  51. }
  52. // nolint reason: res may be not overwriten
  53. func parseQueryInt64(name string, dflt *int64, min, max int64, c querier) (*int64, error) { //nolint:SA4009
  54. str := c.Query(name)
  55. return stringToInt64(str, name, dflt, min, max)
  56. }
  57. // nolint reason: res may be not overwriten
  58. func parseQueryBool(name string, dflt *bool, c querier) (*bool, error) { //nolint:SA4009
  59. str := c.Query(name)
  60. if str == "" {
  61. return dflt, nil
  62. }
  63. if str == "true" {
  64. res := new(bool)
  65. *res = true
  66. return res, nil
  67. }
  68. if str == "false" {
  69. res := new(bool)
  70. *res = false
  71. return res, nil
  72. }
  73. return nil, tracerr.Wrap(fmt.Errorf("Invalid %s. Must be eithe true or false", name))
  74. }
  75. func parseQueryHezEthAddr(c querier) (*ethCommon.Address, error) {
  76. const name = "hermezEthereumAddress"
  77. addrStr := c.Query(name)
  78. return hezStringToEthAddr(addrStr, name)
  79. }
  80. func parseQueryBJJ(c querier) (*babyjub.PublicKey, error) {
  81. const name = "BJJ"
  82. bjjStr := c.Query(name)
  83. if bjjStr == "" {
  84. return nil, nil
  85. }
  86. return hezStringToBJJ(bjjStr, name)
  87. }
  88. func parseQueryTxType(c querier) (*common.TxType, error) {
  89. const name = "type"
  90. typeStr := c.Query(name)
  91. if typeStr == "" {
  92. return nil, nil
  93. }
  94. switch common.TxType(typeStr) {
  95. case common.TxTypeExit:
  96. ret := common.TxTypeExit
  97. return &ret, nil
  98. case common.TxTypeTransfer:
  99. ret := common.TxTypeTransfer
  100. return &ret, nil
  101. case common.TxTypeDeposit:
  102. ret := common.TxTypeDeposit
  103. return &ret, nil
  104. case common.TxTypeCreateAccountDeposit:
  105. ret := common.TxTypeCreateAccountDeposit
  106. return &ret, nil
  107. case common.TxTypeCreateAccountDepositTransfer:
  108. ret := common.TxTypeCreateAccountDepositTransfer
  109. return &ret, nil
  110. case common.TxTypeDepositTransfer:
  111. ret := common.TxTypeDepositTransfer
  112. return &ret, nil
  113. case common.TxTypeForceTransfer:
  114. ret := common.TxTypeForceTransfer
  115. return &ret, nil
  116. case common.TxTypeForceExit:
  117. ret := common.TxTypeForceExit
  118. return &ret, nil
  119. case common.TxTypeTransferToEthAddr:
  120. ret := common.TxTypeTransferToEthAddr
  121. return &ret, nil
  122. case common.TxTypeTransferToBJJ:
  123. ret := common.TxTypeTransferToBJJ
  124. return &ret, nil
  125. }
  126. return nil, tracerr.Wrap(fmt.Errorf(
  127. "invalid %s, %s is not a valid option. Check the valid options in the docmentation",
  128. name, typeStr,
  129. ))
  130. }
  131. func parseIdx(c querier) (*common.Idx, error) {
  132. const name = "accountIndex"
  133. idxStr := c.Query(name)
  134. return stringToIdx(idxStr, name)
  135. }
  136. func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKey, *common.Idx, error) {
  137. // TokenID
  138. tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
  139. if err != nil {
  140. return nil, nil, nil, nil, tracerr.Wrap(err)
  141. }
  142. var tokenID *common.TokenID
  143. if tid != nil {
  144. tokenID = new(common.TokenID)
  145. *tokenID = common.TokenID(*tid)
  146. }
  147. // Hez Eth addr
  148. addr, err := parseQueryHezEthAddr(c)
  149. if err != nil {
  150. return nil, nil, nil, nil, tracerr.Wrap(err)
  151. }
  152. // BJJ
  153. bjj, err := parseQueryBJJ(c)
  154. if err != nil {
  155. return nil, nil, nil, nil, tracerr.Wrap(err)
  156. }
  157. if addr != nil && bjj != nil {
  158. return nil, nil, nil, nil, tracerr.Wrap(errors.New("bjj and hermezEthereumAddress params are incompatible"))
  159. }
  160. // Idx
  161. idx, err := parseIdx(c)
  162. if err != nil {
  163. return nil, nil, nil, nil, tracerr.Wrap(err)
  164. }
  165. if idx != nil && (addr != nil || bjj != nil || tokenID != nil) {
  166. return nil, nil, nil, nil, tracerr.Wrap(errors.New("accountIndex is incompatible with BJJ, hermezEthereumAddress and tokenId"))
  167. }
  168. return tokenID, addr, bjj, idx, nil
  169. }
  170. func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
  171. idsStr := c.Query("ids")
  172. symbolsStr := c.Query("symbols")
  173. nameStr := c.Query("name")
  174. var tokensIDs []common.TokenID
  175. if idsStr != "" {
  176. ids := strings.Split(idsStr, ",")
  177. for _, id := range ids {
  178. idUint, err := strconv.Atoi(id)
  179. if err != nil {
  180. return nil, nil, "", tracerr.Wrap(err)
  181. }
  182. tokenID := common.TokenID(idUint)
  183. tokensIDs = append(tokensIDs, tokenID)
  184. }
  185. }
  186. var symbols []string
  187. if symbolsStr != "" {
  188. symbols = strings.Split(symbolsStr, ",")
  189. }
  190. return tokensIDs, symbols, nameStr, nil
  191. }
  192. func parseBidFilters(c querier) (*int64, *ethCommon.Address, error) {
  193. slotNum, err := parseQueryInt64("slotNum", nil, 0, maxInt64, c)
  194. if err != nil {
  195. return nil, nil, tracerr.Wrap(err)
  196. }
  197. bidderAddr, err := parseQueryEthAddr("bidderAddr", c)
  198. if err != nil {
  199. return nil, nil, tracerr.Wrap(err)
  200. }
  201. return slotNum, bidderAddr, nil
  202. }
  203. func parseSlotFilters(c querier) (*int64, *int64, *ethCommon.Address, *bool, error) {
  204. minSlotNum, err := parseQueryInt64("minSlotNum", nil, 0, maxInt64, c)
  205. if err != nil {
  206. return nil, nil, nil, nil, tracerr.Wrap(err)
  207. }
  208. maxSlotNum, err := parseQueryInt64("maxSlotNum", nil, 0, maxInt64, c)
  209. if err != nil {
  210. return nil, nil, nil, nil, tracerr.Wrap(err)
  211. }
  212. wonByEthereumAddress, err := parseQueryEthAddr("wonByEthereumAddress", c)
  213. if err != nil {
  214. return nil, nil, nil, nil, tracerr.Wrap(err)
  215. }
  216. finishedAuction, err := parseQueryBool("finishedAuction", nil, c)
  217. if err != nil {
  218. return nil, nil, nil, nil, tracerr.Wrap(err)
  219. }
  220. return minSlotNum, maxSlotNum, wonByEthereumAddress, finishedAuction, nil
  221. }
  222. func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *babyjub.PublicKey, error) {
  223. // TokenID
  224. idsStr := c.Query("tokenIds")
  225. var tokenIDs []common.TokenID
  226. if idsStr != "" {
  227. ids := strings.Split(idsStr, ",")
  228. for _, id := range ids {
  229. idUint, err := strconv.Atoi(id)
  230. if err != nil {
  231. return nil, nil, nil, tracerr.Wrap(err)
  232. }
  233. tokenID := common.TokenID(idUint)
  234. tokenIDs = append(tokenIDs, tokenID)
  235. }
  236. }
  237. // Hez Eth addr
  238. addr, err := parseQueryHezEthAddr(c)
  239. if err != nil {
  240. return nil, nil, nil, tracerr.Wrap(err)
  241. }
  242. // BJJ
  243. bjj, err := parseQueryBJJ(c)
  244. if err != nil {
  245. return nil, nil, nil, tracerr.Wrap(err)
  246. }
  247. if addr != nil && bjj != nil {
  248. return nil, nil, nil, tracerr.Wrap(errors.New("bjj and hermezEthereumAddress params are incompatible"))
  249. }
  250. return tokenIDs, addr, bjj, nil
  251. }
  252. // Param parsers
  253. type paramer interface {
  254. Param(string) string
  255. }
  256. func parseParamTxID(c paramer) (common.TxID, error) {
  257. const name = "id"
  258. txIDStr := c.Param(name)
  259. if txIDStr == "" {
  260. return common.TxID{}, tracerr.Wrap(fmt.Errorf("%s is required", name))
  261. }
  262. txID, err := common.NewTxIDFromString(txIDStr)
  263. if err != nil {
  264. return common.TxID{}, tracerr.Wrap(fmt.Errorf("invalid %s", name))
  265. }
  266. return txID, nil
  267. }
  268. func parseParamIdx(c paramer) (*common.Idx, error) {
  269. const name = "accountIndex"
  270. idxStr := c.Param(name)
  271. return stringToIdx(idxStr, name)
  272. }
  273. // nolint reason: res may be not overwriten
  274. func parseParamUint(name string, dflt *uint, min, max uint, c paramer) (*uint, error) { //nolint:SA4009
  275. str := c.Param(name)
  276. return stringToUint(str, name, dflt, min, max)
  277. }
  278. // nolint reason: res may be not overwriten
  279. func parseParamInt64(name string, dflt *int64, min, max int64, c paramer) (*int64, error) { //nolint:SA4009
  280. str := c.Param(name)
  281. return stringToInt64(str, name, dflt, min, max)
  282. }
  283. func stringToIdx(idxStr, name string) (*common.Idx, error) {
  284. if idxStr == "" {
  285. return nil, nil
  286. }
  287. splitted := strings.Split(idxStr, ":")
  288. const expectedLen = 3
  289. if len(splitted) != expectedLen || splitted[0] != "hez" {
  290. return nil, tracerr.Wrap(fmt.Errorf(
  291. "invalid %s, must follow this: hez:<tokenSymbol>:index", name))
  292. }
  293. // TODO: check that the tokenSymbol match the token related to the account index
  294. idxInt, err := strconv.Atoi(splitted[2])
  295. idx := common.Idx(idxInt)
  296. return &idx, tracerr.Wrap(err)
  297. }
  298. func stringToUint(uintStr, name string, dflt *uint, min, max uint) (*uint, error) {
  299. if uintStr != "" {
  300. resInt, err := strconv.Atoi(uintStr)
  301. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  302. return nil, tracerr.Wrap(fmt.Errorf(
  303. "Invalid %s. Must be an integer within the range [%d, %d]",
  304. name, min, max))
  305. }
  306. res := uint(resInt)
  307. return &res, nil
  308. }
  309. return dflt, nil
  310. }
  311. func stringToInt64(uintStr, name string, dflt *int64, min, max int64) (*int64, error) {
  312. if uintStr != "" {
  313. resInt, err := strconv.Atoi(uintStr)
  314. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  315. return nil, tracerr.Wrap(fmt.Errorf(
  316. "Invalid %s. Must be an integer within the range [%d, %d]",
  317. name, min, max))
  318. }
  319. res := int64(resInt)
  320. return &res, nil
  321. }
  322. return dflt, nil
  323. }
  324. func hezStringToEthAddr(addrStr, name string) (*ethCommon.Address, error) {
  325. if addrStr == "" {
  326. return nil, nil
  327. }
  328. splitted := strings.Split(addrStr, "hez:")
  329. if len(splitted) != 2 || len(splitted[1]) != 42 {
  330. return nil, tracerr.Wrap(fmt.Errorf(
  331. "Invalid %s, must follow this regex: ^hez:0x[a-fA-F0-9]{40}$", name))
  332. }
  333. var addr ethCommon.Address
  334. err := addr.UnmarshalText([]byte(splitted[1]))
  335. return &addr, tracerr.Wrap(err)
  336. }
  337. func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
  338. const decodedLen = 33
  339. splitted := strings.Split(bjjStr, "hez:")
  340. if len(splitted) != 2 || len(splitted[1]) != 44 {
  341. return nil, tracerr.Wrap(fmt.Errorf(
  342. "Invalid %s, must follow this regex: ^hez:[A-Za-z0-9+/=]{44}$",
  343. name))
  344. }
  345. decoded, err := base64.RawURLEncoding.DecodeString(splitted[1])
  346. if err != nil {
  347. return nil, tracerr.Wrap(fmt.Errorf(
  348. "Invalid %s, error decoding base64 string: %s",
  349. name, err.Error()))
  350. }
  351. if len(decoded) != decodedLen {
  352. return nil, tracerr.Wrap(fmt.Errorf(
  353. "invalid %s, error decoding base64 string: unexpected byte array length",
  354. name))
  355. }
  356. bjjBytes := [decodedLen - 1]byte{}
  357. copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
  358. sum := bjjBytes[0]
  359. for i := 1; i < len(bjjBytes); i++ {
  360. sum += bjjBytes[i]
  361. }
  362. if decoded[decodedLen-1] != sum {
  363. return nil, tracerr.Wrap(fmt.Errorf("invalid %s, checksum failed",
  364. name))
  365. }
  366. bjjComp := babyjub.PublicKeyComp(bjjBytes)
  367. bjj, err := bjjComp.Decompress()
  368. if err != nil {
  369. return nil, tracerr.Wrap(fmt.Errorf(
  370. "invalid %s, error decompressing public key: %s",
  371. name, err.Error()))
  372. }
  373. return bjj, nil
  374. }
  375. func parseQueryEthAddr(name string, c querier) (*ethCommon.Address, error) {
  376. addrStr := c.Query(name)
  377. if addrStr == "" {
  378. return nil, nil
  379. }
  380. return parseEthAddr(addrStr)
  381. }
  382. func parseParamEthAddr(name string, c paramer) (*ethCommon.Address, error) {
  383. addrStr := c.Param(name)
  384. if addrStr == "" {
  385. return nil, nil
  386. }
  387. return parseEthAddr(addrStr)
  388. }
  389. func parseEthAddr(ethAddrStr string) (*ethCommon.Address, error) {
  390. var addr ethCommon.Address
  391. err := addr.UnmarshalText([]byte(ethAddrStr))
  392. return &addr, tracerr.Wrap(err)
  393. }
  394. func parseParamHezEthAddr(c paramer) (*ethCommon.Address, error) {
  395. const name = "hermezEthereumAddress"
  396. addrStr := c.Param(name)
  397. return hezStringToEthAddr(addrStr, name)
  398. }
  399. type errorMsg struct {
  400. Message string
  401. }
  402. func bjjToString(bjj *babyjub.PublicKey) string {
  403. pkComp := [32]byte(bjj.Compress())
  404. sum := pkComp[0]
  405. for i := 1; i < len(pkComp); i++ {
  406. sum += pkComp[i]
  407. }
  408. bjjSum := append(pkComp[:], sum)
  409. return "hez:" + base64.RawURLEncoding.EncodeToString(bjjSum)
  410. }
  411. func ethAddrToHez(addr ethCommon.Address) string {
  412. return "hez:" + addr.String()
  413. }
  414. func idxToHez(idx common.Idx, tokenSymbol string) string {
  415. return "hez:" + tokenSymbol + ":" + strconv.Itoa(int(idx))
  416. }