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.

286 lines
8.5 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 = TxTypeExit
  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. // BytesUser encodes a L1Tx into []byte
  137. func (tx *L1Tx) BytesUser() ([]byte, error) {
  138. var b [L1UserTxBytesLen]byte
  139. copy(b[0:20], tx.FromEthAddr.Bytes())
  140. pkCompL := tx.FromBJJ.Compress()
  141. pkCompB := SwapEndianness(pkCompL[:])
  142. copy(b[20:52], pkCompB[:])
  143. fromIdxBytes, err := tx.FromIdx.Bytes()
  144. if err != nil {
  145. return nil, err
  146. }
  147. copy(b[52:58], fromIdxBytes[:])
  148. loadAmountFloat16, err := NewFloat16(tx.LoadAmount)
  149. if err != nil {
  150. return nil, err
  151. }
  152. copy(b[58:60], loadAmountFloat16.Bytes())
  153. amountFloat16, err := NewFloat16(tx.Amount)
  154. if err != nil {
  155. return nil, err
  156. }
  157. copy(b[60:62], amountFloat16.Bytes())
  158. copy(b[62:66], tx.TokenID.Bytes())
  159. toIdxBytes, err := tx.ToIdx.Bytes()
  160. if err != nil {
  161. return nil, err
  162. }
  163. copy(b[66:72], toIdxBytes[:])
  164. return b[:], nil
  165. }
  166. // BytesCoordinatorTx encodes a L1CoordinatorTx into []byte
  167. func (tx *L1Tx) BytesCoordinatorTx(compressedSignatureBytes []byte) ([]byte, error) {
  168. var b [L1CoordinatorTxBytesLen]byte
  169. v := compressedSignatureBytes[64]
  170. s := compressedSignatureBytes[32:64]
  171. r := compressedSignatureBytes[0:32]
  172. b[0] = v
  173. copy(b[1:33], s)
  174. copy(b[33:65], r)
  175. pkCompL := tx.FromBJJ.Compress()
  176. pkCompB := SwapEndianness(pkCompL[:])
  177. copy(b[65:97], pkCompB[:])
  178. copy(b[97:101], tx.TokenID.Bytes())
  179. return b[:], nil
  180. }
  181. // L1UserTxFromBytes decodes a L1Tx from []byte
  182. func L1UserTxFromBytes(b []byte) (*L1Tx, error) {
  183. if len(b) != L1UserTxBytesLen {
  184. return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
  185. }
  186. tx := &L1Tx{
  187. UserOrigin: true,
  188. }
  189. var err error
  190. tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
  191. pkCompB := b[20:52]
  192. pkCompL := SwapEndianness(pkCompB)
  193. var pkComp babyjub.PublicKeyComp
  194. copy(pkComp[:], pkCompL)
  195. tx.FromBJJ, err = pkComp.Decompress()
  196. if err != nil {
  197. return nil, err
  198. }
  199. fromIdx, err := IdxFromBytes(b[52:58])
  200. if err != nil {
  201. return nil, err
  202. }
  203. tx.FromIdx = fromIdx
  204. tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
  205. tx.Amount = Float16FromBytes(b[60:62]).BigInt()
  206. tx.TokenID, err = TokenIDFromBytes(b[62:66])
  207. if err != nil {
  208. return nil, err
  209. }
  210. tx.ToIdx, err = IdxFromBytes(b[66:72])
  211. if err != nil {
  212. return nil, err
  213. }
  214. return tx, nil
  215. }
  216. // L1CoordinatorTxFromBytes decodes a L1Tx from []byte
  217. func L1CoordinatorTxFromBytes(b []byte) (*L1Tx, error) {
  218. if len(b) != L1CoordinatorTxBytesLen {
  219. return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
  220. }
  221. bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
  222. bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
  223. tx := &L1Tx{
  224. UserOrigin: false,
  225. }
  226. var err error
  227. // Ethereum adds 27 to v
  228. v := b[0] - byte(27) //nolint:gomnd
  229. s := b[1:33]
  230. r := b[33:65]
  231. pkCompB := b[65:97]
  232. pkCompL := SwapEndianness(pkCompB)
  233. var pkComp babyjub.PublicKeyComp
  234. copy(pkComp[:], pkCompL)
  235. tx.FromBJJ, err = pkComp.Decompress()
  236. if err != nil {
  237. return nil, err
  238. }
  239. tx.TokenID, err = TokenIDFromBytes(b[97:101])
  240. if err != nil {
  241. return nil, err
  242. }
  243. var data []byte
  244. data = append(data, bytesMessage1...)
  245. data = append(data, bytesMessage2...)
  246. data = append(data, pkCompB...)
  247. var signature []byte
  248. signature = append(signature, r[:]...)
  249. signature = append(signature, s[:]...)
  250. signature = append(signature, v)
  251. hash := crypto.Keccak256(data)
  252. pubKeyBytes, err := crypto.Ecrecover(hash, signature)
  253. if err != nil {
  254. return nil, err
  255. }
  256. pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
  257. if err != nil {
  258. return nil, err
  259. }
  260. tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
  261. return tx, nil
  262. }