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.

303 lines
9.2 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
  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. // L1UserTxBytesLen is the length of the byte array that represents the L1Tx
  12. L1UserTxBytesLen = 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 `meddler:"id"`
  26. ToForgeL1TxsNum *int64 `meddler:"to_forge_l1_txs_num"` // toForgeL1TxsNum in which the tx was forged / will be forged
  27. Position int `meddler:"position"`
  28. UserOrigin bool `meddler:"user_origin"` // 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 `meddler:"from_idx,zeroisnull"` // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
  30. FromEthAddr ethCommon.Address `meddler:"from_eth_addr,zeroisnull"`
  31. FromBJJ *babyjub.PublicKey `meddler:"from_bjj,zeroisnull"`
  32. ToIdx Idx `meddler:"to_idx"` // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
  33. TokenID TokenID `meddler:"token_id"`
  34. Amount *big.Int `meddler:"amount,bigint"`
  35. LoadAmount *big.Int `meddler:"load_amount,bigint"`
  36. EthBlockNum int64 `meddler:"eth_block_num"` // Ethereum Block Number in which this L1Tx was added to the queue
  37. Type TxType `meddler:"type"`
  38. BatchNum *BatchNum `meddler:"batch_num"`
  39. }
  40. // NewL1Tx returns the given L1Tx with the TxId & Type parameters calculated
  41. // from the L1Tx values
  42. func NewL1Tx(l1Tx *L1Tx) (*L1Tx, error) {
  43. // calculate TxType
  44. var txType TxType
  45. if l1Tx.FromIdx == 0 {
  46. if l1Tx.ToIdx == Idx(0) {
  47. txType = TxTypeCreateAccountDeposit
  48. } else if l1Tx.ToIdx >= IdxUserThreshold {
  49. txType = TxTypeCreateAccountDepositTransfer
  50. } else {
  51. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
  52. }
  53. } else if l1Tx.FromIdx >= IdxUserThreshold {
  54. if l1Tx.ToIdx == Idx(0) {
  55. txType = TxTypeDeposit
  56. } else if l1Tx.ToIdx == Idx(1) {
  57. txType = TxTypeForceExit
  58. } else if l1Tx.ToIdx >= IdxUserThreshold {
  59. if l1Tx.LoadAmount.Int64() == int64(0) {
  60. txType = TxTypeForceTransfer
  61. } else {
  62. txType = TxTypeDepositTransfer
  63. }
  64. } else {
  65. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid ToIdx value: %d", l1Tx.ToIdx)
  66. }
  67. } else {
  68. return l1Tx, fmt.Errorf("Can not determine type of L1Tx, invalid FromIdx value: %d", l1Tx.FromIdx)
  69. }
  70. if l1Tx.Type != "" && l1Tx.Type != txType {
  71. return l1Tx, fmt.Errorf("L1Tx.Type: %s, should be: %s", l1Tx.Type, txType)
  72. }
  73. l1Tx.Type = txType
  74. txID, err := l1Tx.CalcTxID()
  75. if err != nil {
  76. return nil, err
  77. }
  78. l1Tx.TxID = *txID
  79. return l1Tx, nil
  80. }
  81. // CalcTxID calculates the TxId of the L1Tx
  82. func (tx *L1Tx) CalcTxID() (*TxID, error) {
  83. var txID TxID
  84. if tx.UserOrigin {
  85. if tx.ToForgeL1TxsNum == nil {
  86. return nil, fmt.Errorf("L1Tx.UserOrigin == true && L1Tx.ToForgeL1TxsNum == nil")
  87. }
  88. txID[0] = TxIDPrefixL1UserTx
  89. var toForgeL1TxsNumBytes [8]byte
  90. binary.BigEndian.PutUint64(toForgeL1TxsNumBytes[:], uint64(*tx.ToForgeL1TxsNum))
  91. copy(txID[1:9], toForgeL1TxsNumBytes[:])
  92. } else {
  93. if tx.BatchNum == nil {
  94. return nil, fmt.Errorf("L1Tx.UserOrigin == false && L1Tx.BatchNum == nil")
  95. }
  96. txID[0] = TxIDPrefixL1CoordTx
  97. var batchNumBytes [8]byte
  98. binary.BigEndian.PutUint64(batchNumBytes[:], uint64(*tx.BatchNum))
  99. copy(txID[1:9], batchNumBytes[:])
  100. }
  101. var positionBytes [2]byte
  102. binary.BigEndian.PutUint16(positionBytes[:], uint16(tx.Position))
  103. copy(txID[9:11], positionBytes[:])
  104. return &txID, nil
  105. }
  106. // Tx returns a *Tx from the L1Tx
  107. func (tx L1Tx) Tx() Tx {
  108. f := new(big.Float).SetInt(tx.Amount)
  109. amountFloat, _ := f.Float64()
  110. userOrigin := new(bool)
  111. *userOrigin = tx.UserOrigin
  112. genericTx := Tx{
  113. IsL1: true,
  114. TxID: tx.TxID,
  115. Type: tx.Type,
  116. Position: tx.Position,
  117. FromIdx: tx.FromIdx,
  118. ToIdx: tx.ToIdx,
  119. Amount: tx.Amount,
  120. AmountFloat: amountFloat,
  121. TokenID: tx.TokenID,
  122. ToForgeL1TxsNum: tx.ToForgeL1TxsNum,
  123. UserOrigin: userOrigin,
  124. FromEthAddr: tx.FromEthAddr,
  125. FromBJJ: tx.FromBJJ,
  126. LoadAmount: tx.LoadAmount,
  127. EthBlockNum: tx.EthBlockNum,
  128. }
  129. if tx.LoadAmount != nil {
  130. lf := new(big.Float).SetInt(tx.LoadAmount)
  131. loadAmountFloat, _ := lf.Float64()
  132. genericTx.LoadAmountFloat = &loadAmountFloat
  133. }
  134. return genericTx
  135. }
  136. // BytesGeneric returns the generic representation of a L1Tx. This method is
  137. // used to compute the []byte representation of a L1UserTx, and also to compute
  138. // the L1TxData for the ZKInputs (at the HashGlobalInputs), using this method
  139. // for L1CoordinatorTxs & L1UserTxs (for the ZKInputs case).
  140. func (tx *L1Tx) BytesGeneric() ([]byte, error) {
  141. var b [L1UserTxBytesLen]byte
  142. copy(b[0:20], tx.FromEthAddr.Bytes())
  143. if tx.FromBJJ != nil {
  144. pkCompL := tx.FromBJJ.Compress()
  145. pkCompB := SwapEndianness(pkCompL[:])
  146. copy(b[20:52], pkCompB[:])
  147. }
  148. fromIdxBytes, err := tx.FromIdx.Bytes()
  149. if err != nil {
  150. return nil, err
  151. }
  152. copy(b[52:58], fromIdxBytes[:])
  153. loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
  154. if err != nil {
  155. return nil, err
  156. }
  157. copy(b[58:60], loadAmountFloat16.Bytes())
  158. amountFloat16, err := NewFloat16(tx.Amount)
  159. if err != nil {
  160. return nil, err
  161. }
  162. copy(b[60:62], amountFloat16.Bytes())
  163. copy(b[62:66], tx.TokenID.Bytes())
  164. toIdxBytes, err := tx.ToIdx.Bytes()
  165. if err != nil {
  166. return nil, err
  167. }
  168. copy(b[66:72], toIdxBytes[:])
  169. return b[:], nil
  170. }
  171. // BytesUser encodes a L1UserTx into []byte
  172. func (tx *L1Tx) BytesUser() ([]byte, error) {
  173. if !tx.UserOrigin {
  174. return nil, fmt.Errorf("Can not calculate BytesUser() for a L1CoordinatorTx")
  175. }
  176. return tx.BytesGeneric()
  177. }
  178. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  179. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  180. if tx.UserOrigin {
  181. return nil, fmt.Errorf("Can not calculate BytesCoordinatorTx() for a L1UserTx")
  182. }
  183. var b [L1CoordinatorTxBytesLen]byte
  184. v := compressedSignatureBytes[64]
  185. s := compressedSignatureBytes[32:64]
  186. r := compressedSignatureBytes[0:32]
  187. b[0] = v
  188. copy(b[1:33], s)
  189. copy(b[33:65], r)
  190. pkCompL := tx.FromBJJ.Compress()
  191. pkCompB := SwapEndianness(pkCompL[:])
  192. copy(b[65:97], pkCompB[:])
  193. copy(b[97:101], tx.TokenID.Bytes())
  194. return b[:], nil
  195. }
  196. // L1UserTxFromBytes decodes a L1Tx from []byte
  197. func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
  198. if len(b) != L1UserTxBytesLen {
  199. return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
  200. }
  201. tx := &L1Tx{
  202. UserOrigin: true,
  203. }
  204. var err error
  205. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  206. pkCompB := b[20:52]
  207. pkCompL := SwapEndianness(pkCompB)
  208. var pkComp babyjub.PublicKeyComp
  209. copy(pkComp[:], pkCompL)
  210. tx.FromBJJ, err = pkComp.Decompress()
  211. if err != nil {
  212. return nil, err
  213. }
  214. fromIdx, err := IdxFromBytes(b[52:58])
  215. if err != nil {
  216. return nil, err
  217. }
  218. tx.FromIdx = fromIdx
  219. tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
  220. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  221. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  222. if err != nil {
  223. return nil, err
  224. }
  225. tx.ToIdx, err = IdxFromBytes(b[66:72])
  226. if err != nil {
  227. return nil, err
  228. }
  229. return tx, nil
  230. }
  231. // L1CoordinatorTxFromBytes decodes a L1Tx from []byte
  232. func L1CoordinatorTxFromBytes(b []byte) (*L1Tx, error) {
  233. if len(b) != L1CoordinatorTxBytesLen {
  234. return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
  235. }
  236. bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
  237. bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  238. tx := &L1Tx{
  239. UserOrigin: false,
  240. }
  241. var err error
  242. // Ethereum adds 27 to v
  243. v := b[0] - byte(27) //nolint:gomnd
  244. s := b[1:33]
  245. r := b[33:65]
  246. pkCompB := b[65:97]
  247. pkCompL := SwapEndianness(pkCompB)
  248. var pkComp babyjub.PublicKeyComp
  249. copy(pkComp[:], pkCompL)
  250. tx.FromBJJ, err = pkComp.Decompress()
  251. if err != nil {
  252. return nil, err
  253. }
  254. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  255. if err != nil {
  256. return nil, err
  257. }
  258. var data []byte
  259. data = append(data, bytesMessage1...)
  260. data = append(data, bytesMessage2...)
  261. data = append(data, pkCompB...)
  262. var signature []byte
  263. signature = append(signature, r[:]...)
  264. signature = append(signature, s[:]...)
  265. signature = append(signature, v)
  266. hash := crypto.Keccak256(data)
  267. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  268. if err != nil {
  269. return nil, err
  270. }
  271. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  272. if err != nil {
  273. return nil, err
  274. }
  275. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  276. tx.Amount = big.NewInt(0)
  277. tx.LoadAmount = big.NewInt(0)
  278. return tx, nil
  279. }