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.

296 lines
8.8 KiB

  1. package apitypes
  2. import (
  3. "database/sql/driver"
  4. "encoding/base64"
  5. "encoding/hex"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "math/big"
  10. "strconv"
  11. "strings"
  12. ethCommon "github.com/ethereum/go-ethereum/common"
  13. "github.com/hermeznetwork/hermez-node/common"
  14. "github.com/hermeznetwork/tracerr"
  15. "github.com/iden3/go-iden3-crypto/babyjub"
  16. )
  17. // BigIntStr is used to scan/value *big.Int directly into strings from/to sql DBs.
  18. // It assumes that *big.Int are inserted/fetched to/from the DB using the BigIntMeddler meddler
  19. // defined at github.com/hermeznetwork/hermez-node/db
  20. type BigIntStr string
  21. // NewBigIntStr creates a *BigIntStr from a *big.Int.
  22. // If the provided bigInt is nil the returned *BigIntStr will also be nil
  23. func NewBigIntStr(bigInt *big.Int) *BigIntStr {
  24. if bigInt == nil {
  25. return nil
  26. }
  27. bigIntStr := BigIntStr(bigInt.String())
  28. return &bigIntStr
  29. }
  30. // Scan implements Scanner for database/sql
  31. func (b *BigIntStr) Scan(src interface{}) error {
  32. srcBytes, ok := src.([]byte)
  33. if !ok {
  34. return tracerr.Wrap(fmt.Errorf("can't scan %T into apitypes.BigIntStr", src))
  35. }
  36. // bytes to *big.Int
  37. bigInt := new(big.Int).SetBytes(srcBytes)
  38. // *big.Int to BigIntStr
  39. bigIntStr := NewBigIntStr(bigInt)
  40. if bigIntStr == nil {
  41. return nil
  42. }
  43. *b = *bigIntStr
  44. return nil
  45. }
  46. // Value implements valuer for database/sql
  47. func (b BigIntStr) Value() (driver.Value, error) {
  48. // string to *big.Int
  49. bigInt, ok := new(big.Int).SetString(string(b), 10)
  50. if !ok || bigInt == nil {
  51. return nil, tracerr.Wrap(errors.New("invalid representation of a *big.Int"))
  52. }
  53. // *big.Int to bytes
  54. return bigInt.Bytes(), nil
  55. }
  56. // StrBigInt is used to unmarshal BigIntStr directly into an alias of big.Int
  57. type StrBigInt big.Int
  58. // UnmarshalText unmarshals a StrBigInt
  59. func (s *StrBigInt) UnmarshalText(text []byte) error {
  60. bi, ok := (*big.Int)(s).SetString(string(text), 10)
  61. if !ok {
  62. return tracerr.Wrap(fmt.Errorf("could not unmarshal %s into a StrBigInt", text))
  63. }
  64. *s = StrBigInt(*bi)
  65. return nil
  66. }
  67. // CollectedFees is used to retrieve common.batch.CollectedFee from the DB
  68. type CollectedFees map[common.TokenID]BigIntStr
  69. // UnmarshalJSON unmarshals a json representation of map[common.TokenID]*big.Int
  70. func (c *CollectedFees) UnmarshalJSON(text []byte) error {
  71. bigIntMap := make(map[common.TokenID]*big.Int)
  72. if err := json.Unmarshal(text, &bigIntMap); err != nil {
  73. return tracerr.Wrap(err)
  74. }
  75. *c = CollectedFees(make(map[common.TokenID]BigIntStr))
  76. for k, v := range bigIntMap {
  77. bStr := NewBigIntStr(v)
  78. (CollectedFees(*c)[k]) = *bStr
  79. }
  80. // *c = CollectedFees(bStrMap)
  81. return nil
  82. }
  83. // HezEthAddr is used to scan/value Ethereum Address directly into strings that follow the Ethereum address hez format (^hez:0x[a-fA-F0-9]{40}$) from/to sql DBs.
  84. // It assumes that Ethereum Address are inserted/fetched to/from the DB using the default Scan/Value interface
  85. type HezEthAddr string
  86. // NewHezEthAddr creates a HezEthAddr from an Ethereum addr
  87. func NewHezEthAddr(addr ethCommon.Address) HezEthAddr {
  88. return HezEthAddr("hez:" + addr.String())
  89. }
  90. // ToEthAddr returns an Ethereum Address created from HezEthAddr
  91. func (a HezEthAddr) ToEthAddr() (ethCommon.Address, error) {
  92. addrStr := strings.TrimPrefix(string(a), "hez:")
  93. var addr ethCommon.Address
  94. return addr, addr.UnmarshalText([]byte(addrStr))
  95. }
  96. // Scan implements Scanner for database/sql
  97. func (a *HezEthAddr) Scan(src interface{}) error {
  98. ethAddr := &ethCommon.Address{}
  99. if err := ethAddr.Scan(src); err != nil {
  100. return tracerr.Wrap(err)
  101. }
  102. if ethAddr == nil {
  103. return nil
  104. }
  105. *a = NewHezEthAddr(*ethAddr)
  106. return nil
  107. }
  108. // Value implements valuer for database/sql
  109. func (a HezEthAddr) Value() (driver.Value, error) {
  110. ethAddr, err := a.ToEthAddr()
  111. if err != nil {
  112. return nil, tracerr.Wrap(err)
  113. }
  114. return ethAddr.Value()
  115. }
  116. // StrHezEthAddr is used to unmarshal HezEthAddr directly into an alias of ethCommon.Address
  117. type StrHezEthAddr ethCommon.Address
  118. // UnmarshalText unmarshals a StrHezEthAddr
  119. func (s *StrHezEthAddr) UnmarshalText(text []byte) error {
  120. withoutHez := strings.TrimPrefix(string(text), "hez:")
  121. var addr ethCommon.Address
  122. if err := addr.UnmarshalText([]byte(withoutHez)); err != nil {
  123. return tracerr.Wrap(err)
  124. }
  125. *s = StrHezEthAddr(addr)
  126. return nil
  127. }
  128. // HezBJJ is used to scan/value *babyjub.PublicKeyComp directly into strings that follow the BJJ public key hez format (^hez:[A-Za-z0-9_-]{44}$) from/to sql DBs.
  129. // It assumes that *babyjub.PublicKeyComp are inserted/fetched to/from the DB using the default Scan/Value interface
  130. type HezBJJ string
  131. // NewHezBJJ creates a HezBJJ from a *babyjub.PublicKeyComp.
  132. // Calling this method with a nil bjj causes panic
  133. func NewHezBJJ(pkComp babyjub.PublicKeyComp) HezBJJ {
  134. sum := pkComp[0]
  135. for i := 1; i < len(pkComp); i++ {
  136. sum += pkComp[i]
  137. }
  138. bjjSum := append(pkComp[:], sum)
  139. return HezBJJ("hez:" + base64.RawURLEncoding.EncodeToString(bjjSum))
  140. }
  141. func hezStrToBJJ(s string) (babyjub.PublicKeyComp, error) {
  142. const decodedLen = 33
  143. const encodedLen = 44
  144. formatErr := errors.New("invalid BJJ format. Must follow this regex: ^hez:[A-Za-z0-9_-]{44}$")
  145. encoded := strings.TrimPrefix(s, "hez:")
  146. if len(encoded) != encodedLen {
  147. return common.EmptyBJJComp, formatErr
  148. }
  149. decoded, err := base64.RawURLEncoding.DecodeString(encoded)
  150. if err != nil {
  151. return common.EmptyBJJComp, formatErr
  152. }
  153. if len(decoded) != decodedLen {
  154. return common.EmptyBJJComp, formatErr
  155. }
  156. bjjBytes := [decodedLen - 1]byte{}
  157. copy(bjjBytes[:decodedLen-1], decoded[:decodedLen-1])
  158. sum := bjjBytes[0]
  159. for i := 1; i < len(bjjBytes); i++ {
  160. sum += bjjBytes[i]
  161. }
  162. if decoded[decodedLen-1] != sum {
  163. return common.EmptyBJJComp, tracerr.Wrap(errors.New("checksum verification failed"))
  164. }
  165. bjjComp := babyjub.PublicKeyComp(bjjBytes)
  166. return bjjComp, nil
  167. }
  168. // ToBJJ returns a babyjub.PublicKeyComp created from HezBJJ
  169. func (b HezBJJ) ToBJJ() (babyjub.PublicKeyComp, error) {
  170. return hezStrToBJJ(string(b))
  171. }
  172. // Scan implements Scanner for database/sql
  173. func (b *HezBJJ) Scan(src interface{}) error {
  174. bjj := &babyjub.PublicKeyComp{}
  175. if err := bjj.Scan(src); err != nil {
  176. return tracerr.Wrap(err)
  177. }
  178. if bjj == nil {
  179. return nil
  180. }
  181. *b = NewHezBJJ(*bjj)
  182. return nil
  183. }
  184. // Value implements valuer for database/sql
  185. func (b HezBJJ) Value() (driver.Value, error) {
  186. bjj, err := b.ToBJJ()
  187. if err != nil {
  188. return nil, tracerr.Wrap(err)
  189. }
  190. return bjj.Value()
  191. }
  192. // StrHezBJJ is used to unmarshal HezBJJ directly into an alias of babyjub.PublicKeyComp
  193. type StrHezBJJ babyjub.PublicKeyComp
  194. // UnmarshalText unmarshalls a StrHezBJJ
  195. func (s *StrHezBJJ) UnmarshalText(text []byte) error {
  196. bjj, err := hezStrToBJJ(string(text))
  197. if err != nil {
  198. return tracerr.Wrap(err)
  199. }
  200. *s = StrHezBJJ(bjj)
  201. return nil
  202. }
  203. // HezIdx is used to value common.Idx directly into strings that follow the Idx key hez format (hez:tokenSymbol:idx) to sql DBs.
  204. // Note that this can only be used to insert to DB since there is no way to automatically read from the DB since it needs the tokenSymbol
  205. type HezIdx string
  206. // StrHezIdx is used to unmarshal HezIdx directly into an alias of common.Idx
  207. type StrHezIdx common.Idx
  208. // UnmarshalText unmarshals a StrHezIdx
  209. func (s *StrHezIdx) UnmarshalText(text []byte) error {
  210. withoutHez := strings.TrimPrefix(string(text), "hez:")
  211. splitted := strings.Split(withoutHez, ":")
  212. const expectedLen = 2
  213. if len(splitted) != expectedLen {
  214. return tracerr.Wrap(fmt.Errorf("can not unmarshal %s into StrHezIdx", text))
  215. }
  216. idxInt, err := strconv.Atoi(splitted[1])
  217. if err != nil {
  218. return tracerr.Wrap(err)
  219. }
  220. *s = StrHezIdx(common.Idx(idxInt))
  221. return nil
  222. }
  223. // EthSignature is used to scan/value []byte representing an Ethereum signature directly into strings from/to sql DBs.
  224. type EthSignature string
  225. // NewEthSignature creates a *EthSignature from []byte
  226. // If the provided signature is nil the returned *EthSignature will also be nil
  227. func NewEthSignature(signature []byte) *EthSignature {
  228. if signature == nil {
  229. return nil
  230. }
  231. ethSignature := EthSignature("0x" + hex.EncodeToString(signature))
  232. return &ethSignature
  233. }
  234. // Scan implements Scanner for database/sql
  235. func (e *EthSignature) Scan(src interface{}) error {
  236. if srcStr, ok := src.(string); ok {
  237. // src is a string
  238. *e = *(NewEthSignature([]byte(srcStr)))
  239. return nil
  240. } else if srcBytes, ok := src.([]byte); ok {
  241. // src is []byte
  242. *e = *(NewEthSignature(srcBytes))
  243. return nil
  244. } else {
  245. // unexpected src
  246. return tracerr.Wrap(fmt.Errorf("can't scan %T into apitypes.EthSignature", src))
  247. }
  248. }
  249. // Value implements valuer for database/sql
  250. func (e EthSignature) Value() (driver.Value, error) {
  251. without0x := strings.TrimPrefix(string(e), "0x")
  252. return hex.DecodeString(without0x)
  253. }
  254. // UnmarshalText unmarshals a StrEthSignature
  255. func (e *EthSignature) UnmarshalText(text []byte) error {
  256. without0x := strings.TrimPrefix(string(text), "0x")
  257. signature, err := hex.DecodeString(without0x)
  258. if err != nil {
  259. return tracerr.Wrap(err)
  260. }
  261. *e = EthSignature([]byte(signature))
  262. return nil
  263. }