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