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	// L1TxBytesLen is the length of the byte array that represents the L1Tx
 15	L1TxBytesLen = 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
 31	ToForgeL1TxsNum *int64 // toForgeL1TxsNum in which the tx was forged / will be forged
 32	Position        int
 33	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
 34	FromIdx         Idx  // FromIdx is used by L1Tx/Deposit to indicate the Idx receiver of the L1Tx.LoadAmount (deposit)
 35	FromEthAddr     ethCommon.Address
 36	FromBJJ         *babyjub.PublicKey
 37	ToIdx           Idx // ToIdx is ignored in L1Tx/Deposit, but used in the L1Tx/DepositAndTransfer
 38	TokenID         TokenID
 39	Amount          *big.Int
 40	LoadAmount      *big.Int
 41	EthBlockNum     int64 // Ethereum Block Number in which this L1Tx was added to the queue
 42	Type            TxType
 43	BatchNum        *BatchNum
 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 = TxTypeExit
 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// Bytes encodes a L1Tx into []byte
150func (tx *L1Tx) Bytes() ([]byte, error) {
151	var b [L1TxBytesLen]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// L1TxFromBytes decodes a L1Tx from []byte
197func L1TxFromBytes(b []byte) (*L1Tx, error) {
198	if len(b) != L1TxBytesLen {
199		return nil, fmt.Errorf("Can not parse L1Tx bytes, expected length %d, current: %d", 68, len(b))
200	}
201
202	tx := &L1Tx{}
203	var err error
204	tx.FromEthAddr = ethCommon.BytesToAddress(b[0:20])
205
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
212	if err != nil {
213		return nil, err
214	}
215	fromIdx, err := IdxFromBytes(b[52:58])
216	if err != nil {
217		return nil, err
218	}
219	tx.FromIdx = fromIdx
220	tx.LoadAmount = Float16FromBytes(b[58:60]).BigInt()
221	tx.Amount = Float16FromBytes(b[60:62]).BigInt()
222	tx.TokenID, err = TokenIDFromBytes(b[62:66])
223	if err != nil {
224		return nil, err
225	}
226	tx.ToIdx, err = IdxFromBytes(b[66:72])
227	if err != nil {
228		return nil, err
229	}
230
231	return tx, nil
232}
233
234// L1TxFromCoordinatorBytes decodes a L1Tx from []byte
235func L1TxFromCoordinatorBytes(b []byte) (*L1Tx, error) {
236	if len(b) != L1CoordinatorTxBytesLen {
237		return nil, fmt.Errorf("Can not parse L1CoordinatorTx bytes, expected length %d, current: %d", 101, len(b))
238	}
239
240	bytesMessage1 := []byte("\x19Ethereum Signed Message:\n98")
241	bytesMessage2 := []byte("I authorize this babyjubjub key for hermez rollup account creation")
242
243	tx := &L1Tx{}
244	var err error
245	// Ethereum adds 27 to v
246	v := b[0] - byte(27) //nolint:gomnd
247	s := b[1:33]
248	r := b[33:65]
249
250	pkCompB := b[65:97]
251	pkCompL := SwapEndianness(pkCompB)
252	var pkComp babyjub.PublicKeyComp
253	copy(pkComp[:], pkCompL)
254	tx.FromBJJ, err = pkComp.Decompress()
255	if err != nil {
256		return nil, err
257	}
258	tx.TokenID, err = TokenIDFromBytes(b[97:101])
259	if err != nil {
260		return nil, err
261	}
262
263	var data []byte
264	data = append(data, bytesMessage1...)
265	data = append(data, bytesMessage2...)
266	data = append(data, pkCompB...)
267	var signature []byte
268	signature = append(signature, r[:]...)
269	signature = append(signature, s[:]...)
270	signature = append(signature, v)
271	hash := crypto.Keccak256(data)
272	pubKeyBytes, err := crypto.Ecrecover(hash, signature)
273	if err != nil {
274		return nil, err
275	}
276	pubKey, err := crypto.UnmarshalPubkey(pubKeyBytes)
277	if err != nil {
278		return nil, err
279	}
280	tx.FromEthAddr = crypto.PubkeyToAddress(*pubKey)
281	return tx, nil
282}