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