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.

467 lines
13 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
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 overwritten
  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 overwritten
  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 overwritten
  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 = "hezEthereumAddress"
  77. addrStr := c.Query(name)
  78. return hezStringToEthAddr(addrStr, name)
  79. }
  80. func parseQueryBJJ(c querier) (*babyjub.PublicKeyComp, 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 parseQueryPoolL2TxState(c querier) (*common.PoolL2TxState, error) {
  89. const name = "state"
  90. stateStr := c.Query(name)
  91. if stateStr == "" {
  92. return nil, nil
  93. }
  94. switch common.PoolL2TxState(stateStr) {
  95. case common.PoolL2TxStatePending:
  96. ret := common.PoolL2TxStatePending
  97. return &ret, nil
  98. case common.PoolL2TxStateForged:
  99. ret := common.PoolL2TxStateForged
  100. return &ret, nil
  101. case common.PoolL2TxStateForging:
  102. ret := common.PoolL2TxStateForging
  103. return &ret, nil
  104. case common.PoolL2TxStateInvalid:
  105. ret := common.PoolL2TxStateInvalid
  106. return &ret, nil
  107. }
  108. return nil, tracerr.Wrap(fmt.Errorf(
  109. "invalid %s, %s is not a valid option. Check the valid options in the docmentation",
  110. name, stateStr,
  111. ))
  112. }
  113. func parseQueryTxType(c querier) (*common.TxType, error) {
  114. const name = "type"
  115. typeStr := c.Query(name)
  116. if typeStr == "" {
  117. return nil, nil
  118. }
  119. switch common.TxType(typeStr) {
  120. case common.TxTypeExit:
  121. ret := common.TxTypeExit
  122. return &ret, nil
  123. case common.TxTypeTransfer:
  124. ret := common.TxTypeTransfer
  125. return &ret, nil
  126. case common.TxTypeDeposit:
  127. ret := common.TxTypeDeposit
  128. return &ret, nil
  129. case common.TxTypeCreateAccountDeposit:
  130. ret := common.TxTypeCreateAccountDeposit
  131. return &ret, nil
  132. case common.TxTypeCreateAccountDepositTransfer:
  133. ret := common.TxTypeCreateAccountDepositTransfer
  134. return &ret, nil
  135. case common.TxTypeDepositTransfer:
  136. ret := common.TxTypeDepositTransfer
  137. return &ret, nil
  138. case common.TxTypeForceTransfer:
  139. ret := common.TxTypeForceTransfer
  140. return &ret, nil
  141. case common.TxTypeForceExit:
  142. ret := common.TxTypeForceExit
  143. return &ret, nil
  144. case common.TxTypeTransferToEthAddr:
  145. ret := common.TxTypeTransferToEthAddr
  146. return &ret, nil
  147. case common.TxTypeTransferToBJJ:
  148. ret := common.TxTypeTransferToBJJ
  149. return &ret, nil
  150. }
  151. return nil, tracerr.Wrap(fmt.Errorf(
  152. "invalid %s, %s is not a valid option. Check the valid options in the docmentation",
  153. name, typeStr,
  154. ))
  155. }
  156. func parseIdx(c querier) (*common.Idx, error) {
  157. const name = "accountIndex"
  158. idxStr := c.Query(name)
  159. return stringToIdx(idxStr, name)
  160. }
  161. func parseExitFilters(c querier) (*common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, *common.Idx, error) {
  162. // TokenID
  163. tid, err := parseQueryUint("tokenId", nil, 0, maxUint32, c)
  164. if err != nil {
  165. return nil, nil, nil, nil, tracerr.Wrap(err)
  166. }
  167. var tokenID *common.TokenID
  168. if tid != nil {
  169. tokenID = new(common.TokenID)
  170. *tokenID = common.TokenID(*tid)
  171. }
  172. // Hez Eth addr
  173. addr, err := parseQueryHezEthAddr(c)
  174. if err != nil {
  175. return nil, nil, nil, nil, tracerr.Wrap(err)
  176. }
  177. // BJJ
  178. bjj, err := parseQueryBJJ(c)
  179. if err != nil {
  180. return nil, nil, nil, nil, tracerr.Wrap(err)
  181. }
  182. if addr != nil && bjj != nil {
  183. return nil, nil, nil, nil, tracerr.Wrap(errors.New("bjj and hezEthereumAddress params are incompatible"))
  184. }
  185. // Idx
  186. idx, err := parseIdx(c)
  187. if err != nil {
  188. return nil, nil, nil, nil, tracerr.Wrap(err)
  189. }
  190. if idx != nil && (addr != nil || bjj != nil || tokenID != nil) {
  191. return nil, nil, nil, nil, tracerr.Wrap(errors.New("accountIndex is incompatible with BJJ, hezEthereumAddress and tokenId"))
  192. }
  193. return tokenID, addr, bjj, idx, nil
  194. }
  195. func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
  196. idsStr := c.Query("ids")
  197. symbolsStr := c.Query("symbols")
  198. nameStr := c.Query("name")
  199. var tokensIDs []common.TokenID
  200. if idsStr != "" {
  201. ids := strings.Split(idsStr, ",")
  202. for _, id := range ids {
  203. idUint, err := strconv.Atoi(id)
  204. if err != nil {
  205. return nil, nil, "", tracerr.Wrap(err)
  206. }
  207. tokenID := common.TokenID(idUint)
  208. tokensIDs = append(tokensIDs, tokenID)
  209. }
  210. }
  211. var symbols []string
  212. if symbolsStr != "" {
  213. symbols = strings.Split(symbolsStr, ",")
  214. }
  215. return tokensIDs, symbols, nameStr, nil
  216. }
  217. func parseBidFilters(c querier) (*int64, *ethCommon.Address, error) {
  218. slotNum, err := parseQueryInt64("slotNum", nil, 0, maxInt64, c)
  219. if err != nil {
  220. return nil, nil, tracerr.Wrap(err)
  221. }
  222. bidderAddr, err := parseQueryEthAddr("bidderAddr", c)
  223. if err != nil {
  224. return nil, nil, tracerr.Wrap(err)
  225. }
  226. return slotNum, bidderAddr, nil
  227. }
  228. func parseSlotFilters(c querier) (*int64, *int64, *ethCommon.Address, *bool, error) {
  229. minSlotNum, err := parseQueryInt64("minSlotNum", nil, 0, maxInt64, c)
  230. if err != nil {
  231. return nil, nil, nil, nil, tracerr.Wrap(err)
  232. }
  233. maxSlotNum, err := parseQueryInt64("maxSlotNum", nil, 0, maxInt64, c)
  234. if err != nil {
  235. return nil, nil, nil, nil, tracerr.Wrap(err)
  236. }
  237. wonByEthereumAddress, err := parseQueryEthAddr("wonByEthereumAddress", c)
  238. if err != nil {
  239. return nil, nil, nil, nil, tracerr.Wrap(err)
  240. }
  241. finishedAuction, err := parseQueryBool("finishedAuction", nil, c)
  242. if err != nil {
  243. return nil, nil, nil, nil, tracerr.Wrap(err)
  244. }
  245. return minSlotNum, maxSlotNum, wonByEthereumAddress, finishedAuction, nil
  246. }
  247. func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *babyjub.PublicKeyComp, error) {
  248. // TokenID
  249. idsStr := c.Query("tokenIds")
  250. var tokenIDs []common.TokenID
  251. if idsStr != "" {
  252. ids := strings.Split(idsStr, ",")
  253. for _, id := range ids {
  254. idUint, err := strconv.Atoi(id)
  255. if err != nil {
  256. return nil, nil, nil, tracerr.Wrap(err)
  257. }
  258. tokenID := common.TokenID(idUint)
  259. tokenIDs = append(tokenIDs, tokenID)
  260. }
  261. }
  262. // Hez Eth addr
  263. addr, err := parseQueryHezEthAddr(c)
  264. if err != nil {
  265. return nil, nil, nil, tracerr.Wrap(err)
  266. }
  267. // BJJ
  268. bjj, err := parseQueryBJJ(c)
  269. if err != nil {
  270. return nil, nil, nil, tracerr.Wrap(err)
  271. }
  272. if addr != nil && bjj != nil {
  273. return nil, nil, nil, tracerr.Wrap(errors.New("bjj and hezEthereumAddress params are incompatible"))
  274. }
  275. return tokenIDs, addr, bjj, nil
  276. }
  277. // Param parsers
  278. type paramer interface {
  279. Param(string) string
  280. }
  281. func parseParamTxID(c paramer) (common.TxID, error) {
  282. const name = "id"
  283. txIDStr := c.Param(name)
  284. if txIDStr == "" {
  285. return common.TxID{}, tracerr.Wrap(fmt.Errorf("%s is required", name))
  286. }
  287. txID, err := common.NewTxIDFromString(txIDStr)
  288. if err != nil {
  289. return common.TxID{}, tracerr.Wrap(fmt.Errorf("invalid %s", name))
  290. }
  291. return txID, nil
  292. }
  293. func parseParamIdx(c paramer) (*common.Idx, error) {
  294. const name = "accountIndex"
  295. idxStr := c.Param(name)
  296. return stringToIdx(idxStr, name)
  297. }
  298. // nolint reason: res may be not overwritten
  299. func parseParamUint(name string, dflt *uint, min, max uint, c paramer) (*uint, error) { //nolint:SA4009
  300. str := c.Param(name)
  301. return stringToUint(str, name, dflt, min, max)
  302. }
  303. // nolint reason: res may be not overwritten
  304. func parseParamInt64(name string, dflt *int64, min, max int64, c paramer) (*int64, error) { //nolint:SA4009
  305. str := c.Param(name)
  306. return stringToInt64(str, name, dflt, min, max)
  307. }
  308. func stringToIdx(idxStr, name string) (*common.Idx, error) {
  309. if idxStr == "" {
  310. return nil, nil
  311. }
  312. splitted := strings.Split(idxStr, ":")
  313. const expectedLen = 3
  314. if len(splitted) != expectedLen || splitted[0] != "hez" {
  315. return nil, tracerr.Wrap(fmt.Errorf(
  316. "invalid %s, must follow this: hez:<tokenSymbol>:index", name))
  317. }
  318. // TODO: check that the tokenSymbol match the token related to the account index
  319. idxInt, err := strconv.Atoi(splitted[2])
  320. idx := common.Idx(idxInt)
  321. return &idx, tracerr.Wrap(err)
  322. }
  323. func stringToUint(uintStr, name string, dflt *uint, min, max uint) (*uint, error) {
  324. if uintStr != "" {
  325. resInt, err := strconv.Atoi(uintStr)
  326. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  327. return nil, tracerr.Wrap(fmt.Errorf(
  328. "Invalid %s. Must be an integer within the range [%d, %d]",
  329. name, min, max))
  330. }
  331. res := uint(resInt)
  332. return &res, nil
  333. }
  334. return dflt, nil
  335. }
  336. func stringToInt64(uintStr, name string, dflt *int64, min, max int64) (*int64, error) {
  337. if uintStr != "" {
  338. resInt, err := strconv.Atoi(uintStr)
  339. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  340. return nil, tracerr.Wrap(fmt.Errorf(
  341. "Invalid %s. Must be an integer within the range [%d, %d]",
  342. name, min, max))
  343. }
  344. res := int64(resInt)
  345. return &res, nil
  346. }
  347. return dflt, nil
  348. }
  349. func hezStringToEthAddr(addrStr, name string) (*ethCommon.Address, error) {
  350. if addrStr == "" {
  351. return nil, nil
  352. }
  353. splitted := strings.Split(addrStr, "hez:")
  354. if len(splitted) != 2 || len(splitted[1]) != 42 {
  355. return nil, tracerr.Wrap(fmt.Errorf(
  356. "Invalid %s, must follow this regex: ^hez:0x[a-fA-F0-9]{40}$", name))
  357. }
  358. var addr ethCommon.Address
  359. err := addr.UnmarshalText([]byte(splitted[1]))
  360. return &addr, tracerr.Wrap(err)
  361. }
  362. func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKeyComp, error) {
  363. const decodedLen = 33
  364. splitted := strings.Split(bjjStr, "hez:")
  365. if len(splitted) != 2 || len(splitted[1]) != 44 {
  366. return nil, tracerr.Wrap(fmt.Errorf(
  367. "Invalid %s, must follow this regex: ^hez:[A-Za-z0-9+/=]{44}$",
  368. name))
  369. }
  370. decoded, err := base64.RawURLEncoding.DecodeString(splitted[1])
  371. if err != nil {
  372. return nil, tracerr.Wrap(fmt.Errorf(
  373. "Invalid %s, error decoding base64 string: %s",
  374. name, err.Error()))
  375. }
  376. if len(decoded) != decodedLen {
  377. return nil, tracerr.Wrap(fmt.Errorf(
  378. "invalid %s, error decoding base64 string: unexpected byte array length",
  379. name))
  380. }
  381. bjjBytes := [decodedLen - 1]byte{}
  382. copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
  383. sum := bjjBytes[0]
  384. for i := 1; i < len(bjjBytes); i++ {
  385. sum += bjjBytes[i]
  386. }
  387. if decoded[decodedLen-1] != sum {
  388. return nil, tracerr.Wrap(fmt.Errorf("invalid %s, checksum failed",
  389. name))
  390. }
  391. bjjComp := babyjub.PublicKeyComp(bjjBytes)
  392. return &bjjComp, nil
  393. }
  394. func parseQueryEthAddr(name string, c querier) (*ethCommon.Address, error) {
  395. addrStr := c.Query(name)
  396. if addrStr == "" {
  397. return nil, nil
  398. }
  399. return parseEthAddr(addrStr)
  400. }
  401. func parseEthAddr(ethAddrStr string) (*ethCommon.Address, error) {
  402. var addr ethCommon.Address
  403. err := addr.UnmarshalText([]byte(ethAddrStr))
  404. return &addr, tracerr.Wrap(err)
  405. }
  406. func parseParamHezEthAddr(c paramer) (*ethCommon.Address, error) {
  407. const name = "hezEthereumAddress"
  408. addrStr := c.Param(name)
  409. return hezStringToEthAddr(addrStr, name)
  410. }
  411. type errorMsg struct {
  412. Message string
  413. }
  414. func bjjToString(bjj babyjub.PublicKeyComp) string {
  415. pkComp := [32]byte(bjj)
  416. sum := pkComp[0]
  417. for i := 1; i < len(pkComp); i++ {
  418. sum += pkComp[i]
  419. }
  420. bjjSum := append(pkComp[:], sum)
  421. return "hez:" + base64.RawURLEncoding.EncodeToString(bjjSum)
  422. }
  423. func ethAddrToHez(addr ethCommon.Address) string {
  424. return "hez:" + addr.String()
  425. }
  426. func idxToHez(idx common.Idx, tokenSymbol string) string {
  427. return "hez:" + tokenSymbol + ":" + strconv.Itoa(int(idx))
  428. }