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.

462 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
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/iden3/go-iden3-crypto/babyjub"
  12. )
  13. const exitIdx = "hez:EXIT:1"
  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, 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, 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, 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, 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, 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, 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, err
  151. }
  152. // BJJ
  153. bjj, err := parseQueryBJJ(c)
  154. if err != nil {
  155. return nil, nil, nil, nil, err
  156. }
  157. if addr != nil && bjj != nil {
  158. return nil, nil, nil, nil,
  159. errors.New("bjj and hermezEthereumAddress params are incompatible")
  160. }
  161. // Idx
  162. idx, err := parseIdx(c)
  163. if err != nil {
  164. return nil, nil, nil, nil, err
  165. }
  166. if idx != nil && (addr != nil || bjj != nil || tokenID != nil) {
  167. return nil, nil, nil, nil,
  168. errors.New("accountIndex is incompatible with BJJ, hermezEthereumAddress and tokenId")
  169. }
  170. return tokenID, addr, bjj, idx, nil
  171. }
  172. func parseTokenFilters(c querier) ([]common.TokenID, []string, string, error) {
  173. idsStr := c.Query("ids")
  174. symbolsStr := c.Query("symbols")
  175. nameStr := c.Query("name")
  176. var tokensIDs []common.TokenID
  177. if idsStr != "" {
  178. ids := strings.Split(idsStr, ",")
  179. for _, id := range ids {
  180. idUint, err := strconv.Atoi(id)
  181. if err != nil {
  182. return nil, nil, "", err
  183. }
  184. tokenID := common.TokenID(idUint)
  185. tokensIDs = append(tokensIDs, tokenID)
  186. }
  187. }
  188. var symbols []string
  189. if symbolsStr != "" {
  190. symbols = strings.Split(symbolsStr, ",")
  191. }
  192. return tokensIDs, symbols, nameStr, nil
  193. }
  194. func parseBidFilters(c querier) (*int64, *ethCommon.Address, error) {
  195. slotNum, err := parseQueryInt64("slotNum", nil, 0, maxInt64, c)
  196. if err != nil {
  197. return nil, nil, err
  198. }
  199. bidderAddr, err := parseQueryEthAddr("bidderAddr", c)
  200. if err != nil {
  201. return nil, nil, err
  202. }
  203. return slotNum, bidderAddr, nil
  204. }
  205. func parseSlotFilters(c querier) (*int64, *int64, *ethCommon.Address, *bool, error) {
  206. minSlotNum, err := parseQueryInt64("minSlotNum", nil, 0, maxInt64, c)
  207. if err != nil {
  208. return nil, nil, nil, nil, err
  209. }
  210. maxSlotNum, err := parseQueryInt64("maxSlotNum", nil, 0, maxInt64, c)
  211. if err != nil {
  212. return nil, nil, nil, nil, err
  213. }
  214. wonByEthereumAddress, err := parseQueryEthAddr("wonByEthereumAddress", c)
  215. if err != nil {
  216. return nil, nil, nil, nil, err
  217. }
  218. finishedAuction, err := parseQueryBool("finishedAuction", nil, c)
  219. if err != nil {
  220. return nil, nil, nil, nil, err
  221. }
  222. return minSlotNum, maxSlotNum, wonByEthereumAddress, finishedAuction, nil
  223. }
  224. func parseAccountFilters(c querier) ([]common.TokenID, *ethCommon.Address, *babyjub.PublicKey, error) {
  225. // TokenID
  226. idsStr := c.Query("tokenIds")
  227. var tokenIDs []common.TokenID
  228. if idsStr != "" {
  229. ids := strings.Split(idsStr, ",")
  230. for _, id := range ids {
  231. idUint, err := strconv.Atoi(id)
  232. if err != nil {
  233. return nil, nil, nil, err
  234. }
  235. tokenID := common.TokenID(idUint)
  236. tokenIDs = append(tokenIDs, tokenID)
  237. }
  238. }
  239. // Hez Eth addr
  240. addr, err := parseQueryHezEthAddr(c)
  241. if err != nil {
  242. return nil, nil, nil, err
  243. }
  244. // BJJ
  245. bjj, err := parseQueryBJJ(c)
  246. if err != nil {
  247. return nil, nil, nil, err
  248. }
  249. if addr != nil && bjj != nil {
  250. return nil, nil, nil,
  251. errors.New("bjj and hermezEthereumAddress params are incompatible")
  252. }
  253. return tokenIDs, addr, bjj, nil
  254. }
  255. // Param parsers
  256. type paramer interface {
  257. Param(string) string
  258. }
  259. func parseParamTxID(c paramer) (common.TxID, error) {
  260. const name = "id"
  261. txIDStr := c.Param(name)
  262. if txIDStr == "" {
  263. return common.TxID{}, fmt.Errorf("%s is required", name)
  264. }
  265. txID, err := common.NewTxIDFromString(txIDStr)
  266. if err != nil {
  267. return common.TxID{}, fmt.Errorf("invalid %s", name)
  268. }
  269. return txID, nil
  270. }
  271. func parseParamIdx(c paramer) (*common.Idx, error) {
  272. const name = "accountIndex"
  273. idxStr := c.Param(name)
  274. return stringToIdx(idxStr, name)
  275. }
  276. // nolint reason: res may be not overwriten
  277. func parseParamUint(name string, dflt *uint, min, max uint, c paramer) (*uint, error) { //nolint:SA4009
  278. str := c.Param(name)
  279. return stringToUint(str, name, dflt, min, max)
  280. }
  281. // nolint reason: res may be not overwriten
  282. func parseParamInt64(name string, dflt *int64, min, max int64, c paramer) (*int64, error) { //nolint:SA4009
  283. str := c.Param(name)
  284. return stringToInt64(str, name, dflt, min, max)
  285. }
  286. func stringToIdx(idxStr, name string) (*common.Idx, error) {
  287. if idxStr == "" {
  288. return nil, nil
  289. }
  290. splitted := strings.Split(idxStr, ":")
  291. const expectedLen = 3
  292. if len(splitted) != expectedLen || splitted[0] != "hez" {
  293. return nil, fmt.Errorf(
  294. "invalid %s, must follow this: hez:<tokenSymbol>:index", name)
  295. }
  296. // TODO: check that the tokenSymbol match the token related to the account index
  297. idxInt, err := strconv.Atoi(splitted[2])
  298. idx := common.Idx(idxInt)
  299. return &idx, err
  300. }
  301. func stringToUint(uintStr, name string, dflt *uint, min, max uint) (*uint, error) {
  302. if uintStr != "" {
  303. resInt, err := strconv.Atoi(uintStr)
  304. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  305. return nil, fmt.Errorf(
  306. "Invalid %s. Must be an integer within the range [%d, %d]",
  307. name, min, max)
  308. }
  309. res := uint(resInt)
  310. return &res, nil
  311. }
  312. return dflt, nil
  313. }
  314. func stringToInt64(uintStr, name string, dflt *int64, min, max int64) (*int64, error) {
  315. if uintStr != "" {
  316. resInt, err := strconv.Atoi(uintStr)
  317. if err != nil || resInt < 0 || resInt < int(min) || resInt > int(max) {
  318. return nil, fmt.Errorf(
  319. "Invalid %s. Must be an integer within the range [%d, %d]",
  320. name, min, max)
  321. }
  322. res := int64(resInt)
  323. return &res, nil
  324. }
  325. return dflt, nil
  326. }
  327. func hezStringToEthAddr(addrStr, name string) (*ethCommon.Address, error) {
  328. if addrStr == "" {
  329. return nil, nil
  330. }
  331. splitted := strings.Split(addrStr, "hez:")
  332. if len(splitted) != 2 || len(splitted[1]) != 42 {
  333. return nil, fmt.Errorf(
  334. "Invalid %s, must follow this regex: ^hez:0x[a-fA-F0-9]{40}$", name)
  335. }
  336. var addr ethCommon.Address
  337. err := addr.UnmarshalText([]byte(splitted[1]))
  338. return &addr, err
  339. }
  340. func hezStringToBJJ(bjjStr, name string) (*babyjub.PublicKey, error) {
  341. const decodedLen = 33
  342. splitted := strings.Split(bjjStr, "hez:")
  343. if len(splitted) != 2 || len(splitted[1]) != 44 {
  344. return nil, fmt.Errorf(
  345. "Invalid %s, must follow this regex: ^hez:[A-Za-z0-9+/=]{44}$",
  346. name)
  347. }
  348. decoded, err := base64.RawURLEncoding.DecodeString(splitted[1])
  349. if err != nil {
  350. return nil, fmt.Errorf(
  351. "Invalid %s, error decoding base64 string: %s",
  352. name, err.Error())
  353. }
  354. if len(decoded) != decodedLen {
  355. return nil, fmt.Errorf(
  356. "invalid %s, error decoding base64 string: unexpected byte array length",
  357. name)
  358. }
  359. bjjBytes := [decodedLen - 1]byte{}
  360. copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
  361. sum := bjjBytes[0]
  362. for i := 1; i < len(bjjBytes); i++ {
  363. sum += bjjBytes[i]
  364. }
  365. if decoded[decodedLen-1] != sum {
  366. return nil, fmt.Errorf("invalid %s, checksum failed",
  367. name)
  368. }
  369. bjjComp := babyjub.PublicKeyComp(bjjBytes)
  370. bjj, err := bjjComp.Decompress()
  371. if err != nil {
  372. return nil, fmt.Errorf(
  373. "invalid %s, error decompressing public key: %s",
  374. name, err.Error())
  375. }
  376. return bjj, nil
  377. }
  378. func parseQueryEthAddr(name string, c querier) (*ethCommon.Address, error) {
  379. addrStr := c.Query(name)
  380. if addrStr == "" {
  381. return nil, nil
  382. }
  383. return parseEthAddr(addrStr)
  384. }
  385. func parseParamEthAddr(name string, c paramer) (*ethCommon.Address, error) {
  386. addrStr := c.Param(name)
  387. if addrStr == "" {
  388. return nil, nil
  389. }
  390. return parseEthAddr(addrStr)
  391. }
  392. func parseEthAddr(ethAddrStr string) (*ethCommon.Address, error) {
  393. var addr ethCommon.Address
  394. err := addr.UnmarshalText([]byte(ethAddrStr))
  395. return &addr, err
  396. }
  397. func parseParamHezEthAddr(c paramer) (*ethCommon.Address, error) {
  398. const name = "hermezEthereumAddress"
  399. addrStr := c.Param(name)
  400. return hezStringToEthAddr(addrStr, name)
  401. }
  402. type errorMsg struct {
  403. Message string
  404. }
  405. func bjjToString(bjj *babyjub.PublicKey) string {
  406. pkComp := [32]byte(bjj.Compress())
  407. sum := pkComp[0]
  408. for i := 1; i < len(pkComp); i++ {
  409. sum += pkComp[i]
  410. }
  411. bjjSum := append(pkComp[:], sum)
  412. return "hez:" + base64.RawURLEncoding.EncodeToString(bjjSum)
  413. }
  414. func ethAddrToHez(addr ethCommon.Address) string {
  415. return "hez:" + addr.String()
  416. }
  417. func idxToHez(idx common.Idx, tokenSymbol string) string {
  418. if idx == 1 {
  419. return exitIdx
  420. }
  421. return "hez:" + tokenSymbol + ":" + strconv.Itoa(int(idx))
  422. }