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