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.

271 lines
7.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package common
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "math/big"
  6. ethCommon "github.com/ethereum/go-ethereum/common"
  7. "github.com/ethereum/go-ethereum/crypto"
  8. "github.com/iden3/go-iden3-crypto/babyjub"
  9. )
  10. const (
  11. // L1TxBytesLen is the length of the byte array that represents the L1Tx
  12. L1TxBytesLen = 72
  13. // L1CoordinatorTxBytesLen is the length of the byte array that represents the L1CoordinatorTx
  14. L1CoordinatorTxBytesLen = 101
  15. )
  16. // L1Tx is a struct that represents a L1 tx
  17. type L1Tx struct {
  18. // Stored in DB: mandatory fileds
  19. // TxID (12 bytes) for L1Tx is:
  20. // bytes: | 1 | 8 | 2 | 1 |
  21. // values: | type | ToForgeL1TxsNum | Position | 0 (padding) |
  22. // where type:
  23. // - L1UserTx: 0
  24. // - L1CoordinatorTx: 1
  25. TxID TxID
  26. ToForgeL1TxsNum *int64 // toForgeL1TxsNum in which the tx was forged / will be forged
  27. Position int
  28. UserOrigin bool // true if the tx was originated by a user, false if it was aoriginated by a coordinator. Note that this differ from the spec for implementation simplification purpposes
  29. FromIdx *Idx // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
  30. FromEthAddr ethCommon.Address
  31. FromBJJ *babyjub.PublicKey
  32. ToIdx Idx // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
  33. TokenID TokenID
  34. Amount *big.Int
  35. LoadAmount *big.Int
  36. EthBlockNum int64 // Ethereum Block Number in which this L1Tx was added to the queue
  37. Type TxType
  38. BatchNum *BatchNum
  39. USD *float64
  40. LoadAmountUSD *float64
  41. }
  42. // NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
  43. // from the L1Tx values
  44. func NewL1Tx(l1Tx *L1Tx) (*L1Tx, error) {
  45. // calculate TxType
  46. var txType TxType
  47. if l1Tx.FromIdx == nil {
  48. if l1Tx.ToIdx == Idx(0) {
  49. txType = TxTypeCreateAccountDeposit
  50. } else if l1Tx.ToIdx >= IdxUserThreshold {
  51. txType = TxTypeCreateAccountDepositTransfer
  52. } else {
  53. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
  54. }
  55. } else if *l1Tx.FromIdx >= IdxUserThreshold {
  56. if l1Tx.ToIdx == Idx(0) {
  57. txType = TxTypeDeposit
  58. } else if l1Tx.ToIdx == Idx(1) {
  59. txType = TxTypeExit
  60. } else if l1Tx.ToIdx >= IdxUserThreshold {
  61. if l1Tx.LoadAmount.Int64() == int64(0) {
  62. txType = TxTypeForceTransfer
  63. } else {
  64. txType = TxTypeDepositTransfer
  65. }
  66. } else {
  67. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
  68. }
  69. } else {
  70. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)
  71. }
  72. if l1Tx.Type != "" && l1Tx.Type != txType {
  73. return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)
  74. }
  75. l1Tx.Type = txType
  76. var txid [TxIDLen]byte
  77. if !l1Tx.UserOrigin {
  78. txid[0] = TxIDPrefixL1CoordTx
  79. }
  80. var toForgeL1TxsNumBytes [8]byte
  81. var toForge uint64 = 0
  82. if l1Tx.ToForgeL1TxsNum != nil {
  83. toForge = uint64(*l1Tx.ToForgeL1TxsNum)
  84. }
  85. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], toForge)
  86. copy(txid[1:9], toForgeL1TxsNumBytes[:])
  87. var positionBytes [2]byte
  88. binary.BigEndian.PutUint16(positionBytes[:], uint16(l1Tx.Position))
  89. copy(txid[9:11], positionBytes[:])
  90. l1Tx.TxID = TxID(txid)
  91. return l1Tx, nil
  92. }
  93. // Tx returns a *Tx from the L1Tx
  94. func (tx *L1Tx) Tx() *Tx {
  95. f := new(big.Float).SetInt(tx.Amount)
  96. amountFloat, _ := f.Float64()
  97. userOrigin := new(bool)
  98. *userOrigin = tx.UserOrigin
  99. fromEthAddr := new(ethCommon.Address)
  100. *fromEthAddr = tx.FromEthAddr
  101. toIdx := new(Idx)
  102. *toIdx = tx.ToIdx
  103. genericTx := &Tx{
  104. IsL1: true,
  105. TxID: tx.TxID,
  106. Type: tx.Type,
  107. Position: tx.Position,
  108. FromIdx: tx.FromIdx,
  109. ToIdx: toIdx,
  110. Amount: tx.Amount,
  111. AmountFloat: amountFloat,
  112. TokenID: tx.TokenID,
  113. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  114. UserOrigin: userOrigin,
  115. FromEthAddr: fromEthAddr,
  116. FromBJJ: tx.FromBJJ,
  117. LoadAmount: tx.LoadAmount,
  118. EthBlockNum: tx.EthBlockNum,
  119. USD: tx.USD,
  120. LoadAmountUSD: tx.LoadAmountUSD,
  121. }
  122. if tx.LoadAmount != nil {
  123. lf := new(big.Float).SetInt(tx.LoadAmount)
  124. loadAmountFloat, _ := lf.Float64()
  125. genericTx.LoadAmountFloat = &loadAmountFloat
  126. }
  127. return genericTx
  128. }
  129. // Bytes encodes a L1Tx into []byte
  130. func (tx *L1Tx) Bytes() ([]byte, error) {
  131. var b [L1TxBytesLen]byte
  132. copy(b[0:20], tx.FromEthAddr.Bytes())
  133. pkComp := tx.FromBJJ.Compress()
  134. copy(b[20:52], pkComp[:])
  135. fromIdxBytes, err := tx.FromIdx.Bytes()
  136. if err != nil {
  137. return nil, err
  138. }
  139. copy(b[52:58], fromIdxBytes[:])
  140. loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
  141. if err != nil {
  142. return nil, err
  143. }
  144. copy(b[58:60], loadAmountFloat16.Bytes())
  145. amountFloat16, err := NewFloat16(tx.Amount)
  146. if err != nil {
  147. return nil, err
  148. }
  149. copy(b[60:62], amountFloat16.Bytes())
  150. copy(b[62:66], tx.TokenID.Bytes())
  151. toIdxBytes, err := tx.ToIdx.Bytes()
  152. if err != nil {
  153. return nil, err
  154. }
  155. copy(b[66:72], toIdxBytes[:])
  156. return b[:], nil
  157. }
  158. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  159. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  160. var b [L1CoordinatorTxBytesLen]byte
  161. v := compressedSignatureBytes[64]
  162. s := compressedSignatureBytes[32:64]
  163. r := compressedSignatureBytes[0:32]
  164. b[0] = v
  165. copy(b[1:33], s)
  166. copy(b[33:65], r)
  167. pkComp := tx.FromBJJ.Compress()
  168. copy(b[65:97], pkComp[:])
  169. copy(b[97:101], tx.TokenID.Bytes())
  170. return b[:], nil
  171. }
  172. // L1TxFromBytes decodes a L1Tx from []byte
  173. func L1TxFromBytes(b []byte) (*L1Tx, error) {
  174. if len(b) != L1TxBytesLen {
  175. return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
  176. }
  177. tx := &L1Tx{}
  178. var err error
  179. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  180. pkCompB := b[20:52]
  181. var pkComp babyjub.PublicKeyComp
  182. copy(pkComp[:], pkCompB)
  183. tx.FromBJJ, err = pkComp.Decompress()
  184. if err != nil {
  185. return nil, err
  186. }
  187. fromIdx, err := IdxFromBytes(b[52:58])
  188. if err != nil {
  189. return nil, err
  190. }
  191. if fromIdx != 0 {
  192. tx.FromIdx = new(Idx)
  193. *tx.FromIdx = fromIdx
  194. }
  195. tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
  196. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  197. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  198. if err != nil {
  199. return nil, err
  200. }
  201. tx.ToIdx, err = IdxFromBytes(b[66:72])
  202. if err != nil {
  203. return nil, err
  204. }
  205. return tx, nil
  206. }
  207. // L1TxFromCoordinatorBytes decodes a L1Tx from []byte
  208. func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
  209. if len(b) != L1CoordinatorTxBytesLen {
  210. return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
  211. }
  212. bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
  213. bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  214. tx := &L1Tx{}
  215. var err error
  216. // Ethereum adds 27 to v
  217. v := b[0] - byte(27) //nolint:gomnd
  218. s := b[1:33]
  219. r := b[33:65]
  220. pkCompB := b[65:97]
  221. var pkComp babyjub.PublicKeyComp
  222. copy(pkComp[:], pkCompB)
  223. tx.FromBJJ, err = pkComp.Decompress()
  224. if err != nil {
  225. return nil, err
  226. }
  227. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  228. if err != nil {
  229. return nil, err
  230. }
  231. var data []byte
  232. data = append(data, bytesMessage1...)
  233. data = append(data, bytesMessage2...)
  234. data = append(data, pkCompB...)
  235. var signature []byte
  236. signature = append(signature, r[:]...)
  237. signature = append(signature, s[:]...)
  238. signature = append(signature, v)
  239. hash := crypto.Keccak256(data)
  240. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  241. if err != nil {
  242. return nil, err
  243. }
  244. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  245. if err != nil {
  246. return nil, err
  247. }
  248. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  249. return tx, nil
  250. }