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.

257 lines
7.3 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 == Idx(0) {
  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. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(l1Tx.ToForgeL1TxsNum))
  82. copy(txid[1:9], toForgeL1TxsNumBytes[:])
  83. var positionBytes [2]byte
  84. binary.BigEndian.PutUint16(positionBytes[:], uint16(l1Tx.Position))
  85. copy(txid[9:11], positionBytes[:])
  86. l1Tx.TxID = TxID(txid)
  87. return l1Tx, nil
  88. }
  89. // Tx returns a *Tx from the L1Tx
  90. func (tx *L1Tx) Tx() *Tx {
  91. f := new(big.Float).SetInt(tx.Amount)
  92. amountFloat, _ := f.Float64()
  93. genericTx := &Tx{
  94. IsL1: true,
  95. TxID: tx.TxID,
  96. Type: tx.Type,
  97. Position: tx.Position,
  98. FromIdx: tx.FromIdx,
  99. ToIdx: tx.ToIdx,
  100. Amount: tx.Amount,
  101. AmountFloat: amountFloat,
  102. TokenID: tx.TokenID,
  103. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  104. UserOrigin: tx.UserOrigin,
  105. FromEthAddr: tx.FromEthAddr,
  106. FromBJJ: tx.FromBJJ,
  107. LoadAmount: tx.LoadAmount,
  108. EthBlockNum: tx.EthBlockNum,
  109. USD: tx.USD,
  110. LoadAmountUSD: tx.LoadAmountUSD,
  111. }
  112. if tx.LoadAmount != nil {
  113. lf := new(big.Float).SetInt(tx.LoadAmount)
  114. loadAmountFloat, _ := lf.Float64()
  115. genericTx.LoadAmountFloat = &loadAmountFloat
  116. }
  117. return genericTx
  118. }
  119. // Bytes encodes a L1Tx into []byte
  120. func (tx *L1Tx) Bytes() ([]byte, error) {
  121. var b [L1TxBytesLen]byte
  122. copy(b[0:20], tx.FromEthAddr.Bytes())
  123. pkComp := tx.FromBJJ.Compress()
  124. copy(b[20:52], pkComp[:])
  125. fromIdxBytes, err := tx.FromIdx.Bytes()
  126. if err != nil {
  127. return nil, err
  128. }
  129. copy(b[52:58], fromIdxBytes[:])
  130. loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
  131. if err != nil {
  132. return nil, err
  133. }
  134. copy(b[58:60], loadAmountFloat16.Bytes())
  135. amountFloat16, err := NewFloat16(tx.Amount)
  136. if err != nil {
  137. return nil, err
  138. }
  139. copy(b[60:62], amountFloat16.Bytes())
  140. copy(b[62:66], tx.TokenID.Bytes())
  141. toIdxBytes, err := tx.ToIdx.Bytes()
  142. if err != nil {
  143. return nil, err
  144. }
  145. copy(b[66:72], toIdxBytes[:])
  146. return b[:], nil
  147. }
  148. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  149. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  150. var b [L1CoordinatorTxBytesLen]byte
  151. v := compressedSignatureBytes[64]
  152. s := compressedSignatureBytes[32:64]
  153. r := compressedSignatureBytes[0:32]
  154. b[0] = v
  155. copy(b[1:33], s)
  156. copy(b[33:65], r)
  157. pkComp := tx.FromBJJ.Compress()
  158. copy(b[65:97], pkComp[:])
  159. copy(b[97:101], tx.TokenID.Bytes())
  160. return b[:], nil
  161. }
  162. // L1TxFromBytes decodes a L1Tx from []byte
  163. func L1TxFromBytes(b []byte) (*L1Tx, error) {
  164. if len(b) != L1TxBytesLen {
  165. return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
  166. }
  167. tx := &L1Tx{}
  168. var err error
  169. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  170. pkCompB := b[20:52]
  171. var pkComp babyjub.PublicKeyComp
  172. copy(pkComp[:], pkCompB)
  173. tx.FromBJJ, err = pkComp.Decompress()
  174. if err != nil {
  175. return nil, err
  176. }
  177. tx.FromIdx, err = IdxFromBytes(b[52:58])
  178. if err != nil {
  179. return nil, err
  180. }
  181. tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
  182. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  183. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  184. if err != nil {
  185. return nil, err
  186. }
  187. tx.ToIdx, err = IdxFromBytes(b[66:72])
  188. if err != nil {
  189. return nil, err
  190. }
  191. return tx, nil
  192. }
  193. // L1TxFromCoordinatorBytes decodes a L1Tx from []byte
  194. func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
  195. if len(b) != L1CoordinatorTxBytesLen {
  196. return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
  197. }
  198. bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
  199. bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  200. tx := &L1Tx{}
  201. var err error
  202. // Ethereum adds 27 to v
  203. v := b[0] - byte(27) //nolint:gomnd
  204. s := b[1:33]
  205. r := b[33:65]
  206. pkCompB := b[65:97]
  207. var pkComp babyjub.PublicKeyComp
  208. copy(pkComp[:], pkCompB)
  209. tx.FromBJJ, err = pkComp.Decompress()
  210. if err != nil {
  211. return nil, err
  212. }
  213. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  214. if err != nil {
  215. return nil, err
  216. }
  217. var data []byte
  218. data = append(data, bytesMessage1...)
  219. data = append(data, bytesMessage2...)
  220. data = append(data, pkCompB...)
  221. var signature []byte
  222. signature = append(signature, r[:]...)
  223. signature = append(signature, s[:]...)
  224. signature = append(signature, v)
  225. hash := crypto.Keccak256(data)
  226. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  227. if err != nil {
  228. return nil, err
  229. }
  230. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  231. if err != nil {
  232. return nil, err
  233. }
  234. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  235. return tx, nil
  236. }