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.

312 lines
9.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
  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, chainID *big.Int, hermezAddress ethCommon.Address) (*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:\n120")
  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. v := b[0]
  243. s := b[1:33]
  244. r := b[33:65]
  245. pkCompB := b[65:97]
  246. pkCompL := SwapEndianness(pkCompB)
  247. var pkComp babyjub.PublicKeyComp
  248. copy(pkComp[:], pkCompL)
  249. tx.FromBJJ, err = pkComp.Decompress()
  250. if err != nil {
  251. return nil, err
  252. }
  253. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  254. if err != nil {
  255. return nil, err
  256. }
  257. tx.Amount = big.NewInt(0)
  258. tx.LoadAmount = big.NewInt(0)
  259. if int(v) > 0 {
  260. // L1CoordinatorTX ETH
  261. // Ethereum adds 27 to v
  262. v = b[0] - byte(27) //nolint:gomnd
  263. chainIDBytes := ethCommon.LeftPadBytes(chainID.Bytes(), 2)
  264. hermezAddressBytes := ethCommon.LeftPadBytes(hermezAddress.Bytes(), 32)
  265. var data []byte
  266. data = append(data, bytesMessage1...)
  267. data = append(data, bytesMessage2...)
  268. data = append(data, pkCompB...)
  269. data = append(data, chainIDBytes[:]...)
  270. data = append(data, hermezAddressBytes...)
  271. var signature []byte
  272. signature = append(signature, r[:]...)
  273. signature = append(signature, s[:]...)
  274. signature = append(signature, v)
  275. hash := crypto.Keccak256(data)
  276. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  277. if err != nil {
  278. return nil, err
  279. }
  280. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  281. if err != nil {
  282. return nil, err
  283. }
  284. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  285. } else {
  286. // L1Coordinator Babyjub
  287. tx.FromEthAddr = RollupConstEthAddressInternalOnly
  288. }
  289. return tx, nil
  290. }