github.com/klaytn/klaytn@v1.10.2/blockchain/types/transaction_test.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from core/types/transaction_test.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package types 22 23 import ( 24 "bytes" 25 "crypto/ecdsa" 26 "encoding/hex" 27 "encoding/json" 28 "fmt" 29 "math/big" 30 "math/rand" 31 "reflect" 32 "sort" 33 "testing" 34 "time" 35 36 "github.com/klaytn/klaytn/blockchain/types/accountkey" 37 "github.com/klaytn/klaytn/common" 38 "github.com/klaytn/klaytn/crypto" 39 "github.com/klaytn/klaytn/params" 40 "github.com/klaytn/klaytn/rlp" 41 "github.com/stretchr/testify/assert" 42 ) 43 44 // The values in those tests are from the Transaction Tests 45 // at github.com/ethereum/tests. 46 var ( 47 testAddr = common.HexToAddress("b94f5374fce5edbc8e2a8697c15331677e6ebf0b") 48 49 emptyTx = NewTransaction( 50 0, 51 common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), 52 big.NewInt(0), 0, big.NewInt(0), 53 nil, 54 ) 55 56 rightvrsTx, _ = NewTransaction( 57 3, 58 testAddr, 59 big.NewInt(10), 60 2000, 61 big.NewInt(1), 62 common.FromHex("5544"), 63 ).WithSignature( 64 LatestSignerForChainID(common.Big1), 65 common.Hex2Bytes("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a301"), 66 ) 67 68 accessListTx = TxInternalDataEthereumAccessList{ 69 ChainID: big.NewInt(1), 70 AccountNonce: 3, 71 Recipient: &testAddr, 72 Amount: big.NewInt(10), 73 GasLimit: 25000, 74 Price: big.NewInt(1), 75 Payload: common.FromHex("5544"), 76 } 77 78 accessAddr = common.HexToAddress("0x0000000000000000000000000000000000000001") 79 dynamicFeeTx = TxInternalDataEthereumDynamicFee{ 80 ChainID: big.NewInt(1), 81 AccountNonce: 3, 82 Recipient: &testAddr, 83 Amount: big.NewInt(10), 84 GasLimit: 25000, 85 GasFeeCap: big.NewInt(1), 86 GasTipCap: big.NewInt(1), 87 Payload: common.FromHex("5544"), 88 AccessList: AccessList{{Address: accessAddr, StorageKeys: []common.Hash{{0}}}}, 89 } 90 91 emptyEip2718Tx = &Transaction{ 92 data: &accessListTx, 93 } 94 95 emptyEip1559Tx = &Transaction{ 96 data: &dynamicFeeTx, 97 } 98 99 signedEip2718Tx, _ = emptyEip2718Tx.WithSignature( 100 NewEIP2930Signer(big.NewInt(1)), 101 common.Hex2Bytes("c9519f4f2b30335884581971573fadf60c6204f59a911df35ee8a540456b266032f1e8e2c5dd761f9e4f88f41c8310aeaba26a8bfcdacfedfa12ec3862d3752101"), 102 ) 103 104 signedEip1559Tx, _ = emptyEip1559Tx.WithSignature( 105 NewLondonSigner(big.NewInt(1)), 106 common.Hex2Bytes("c9519f4f2b30335884581971573fadf60c6204f59a911df35ee8a540456b266032f1e8e2c5dd761f9e4f88f41c8310aeaba26a8bfcdacfedfa12ec3862d3752101")) 107 ) 108 109 func TestTransactionSigHash(t *testing.T) { 110 signer := LatestSignerForChainID(common.Big1) 111 if signer.Hash(emptyTx) != common.HexToHash("a715f8447b97e3105d2cc0a8aca1466fa3a02f7cc6d2f9a3fe89f2581c9111c5") { 112 t.Errorf("empty transaction hash mismatch, ɡot %x", signer.Hash(emptyTx)) 113 } 114 if signer.Hash(rightvrsTx) != common.HexToHash("bd63ce94e66c7ffbce3b61023bbf9ee6df36047525b123201dcb5c4332f105ae") { 115 t.Errorf("RightVRS transaction hash mismatch, ɡot %x", signer.Hash(rightvrsTx)) 116 } 117 } 118 119 func TestEIP2718TransactionSigHash(t *testing.T) { 120 s := NewEIP2930Signer(big.NewInt(1)) 121 if s.Hash(emptyEip2718Tx) != common.HexToHash("49b486f0ec0a60dfbbca2d30cb07c9e8ffb2a2ff41f29a1ab6737475f6ff69f3") { 122 t.Errorf("empty EIP-2718 transaction hash mismatch, got %x", s.Hash(emptyEip2718Tx)) 123 } 124 if s.Hash(signedEip2718Tx) != common.HexToHash("49b486f0ec0a60dfbbca2d30cb07c9e8ffb2a2ff41f29a1ab6737475f6ff69f3") { 125 t.Errorf("signed EIP-2718 transaction hash mismatch, got %x", s.Hash(signedEip2718Tx)) 126 } 127 } 128 129 func TestEIP1559TransactionSigHash(t *testing.T) { 130 s := NewLondonSigner(big.NewInt(1)) 131 if s.Hash(emptyEip1559Tx) != common.HexToHash("a52ce25a7d108740bce8fbb2dfa1f26793b2e8eea94a7700bedbae13cbdd8a0f") { 132 t.Errorf("empty EIP-1559 transaction hash mismatch, got %x", s.Hash(emptyEip2718Tx)) 133 } 134 if s.Hash(signedEip1559Tx) != common.HexToHash("a52ce25a7d108740bce8fbb2dfa1f26793b2e8eea94a7700bedbae13cbdd8a0f") { 135 t.Errorf("signed EIP-1559 transaction hash mismatch, got %x", s.Hash(signedEip2718Tx)) 136 } 137 } 138 139 // This test checks signature operations on access list transactions. 140 func TestEIP2930Signer(t *testing.T) { 141 var ( 142 key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 143 keyAddr = crypto.PubkeyToAddress(key.PublicKey) 144 signer1 = NewEIP2930Signer(big.NewInt(1)) 145 signer2 = NewEIP2930Signer(big.NewInt(2)) 146 tx0 = NewTx(&TxInternalDataEthereumAccessList{AccountNonce: 1, ChainID: new(big.Int)}) 147 tx1 = NewTx(&TxInternalDataEthereumAccessList{ChainID: big.NewInt(1), AccountNonce: 1, V: new(big.Int), R: new(big.Int), S: new(big.Int)}) 148 tx2, _ = SignTx(NewTx(&TxInternalDataEthereumAccessList{ChainID: big.NewInt(2), AccountNonce: 1}), signer2, key) 149 ) 150 151 tests := []struct { 152 tx *Transaction 153 signer Signer 154 wantSignerHash common.Hash 155 wantSenderErr error 156 wantSignErr error 157 wantHash common.Hash // after signing 158 }{ 159 { 160 tx: tx0, 161 signer: signer1, 162 wantSignerHash: common.HexToHash("846ad7672f2a3a40c1f959cd4a8ad21786d620077084d84c8d7c077714caa139"), 163 wantSenderErr: ErrInvalidChainId, 164 wantHash: common.HexToHash("1ccd12d8bbdb96ea391af49a35ab641e219b2dd638dea375f2bc94dd290f2549"), 165 }, 166 { 167 tx: tx1, 168 signer: signer1, 169 wantSenderErr: ErrInvalidSig, 170 wantSignerHash: common.HexToHash("846ad7672f2a3a40c1f959cd4a8ad21786d620077084d84c8d7c077714caa139"), 171 wantHash: common.HexToHash("1ccd12d8bbdb96ea391af49a35ab641e219b2dd638dea375f2bc94dd290f2549"), 172 }, 173 { 174 // This checks what happens when trying to sign an unsigned tx for the wrong chain. 175 tx: tx1, 176 signer: signer2, 177 wantSenderErr: ErrInvalidChainId, 178 wantSignerHash: common.HexToHash("846ad7672f2a3a40c1f959cd4a8ad21786d620077084d84c8d7c077714caa139"), 179 wantSignErr: ErrInvalidChainId, 180 }, 181 { 182 // This checks what happens when trying to re-sign a signed tx for the wrong chain. 183 tx: tx2, 184 signer: signer1, 185 wantSenderErr: ErrInvalidChainId, 186 wantSignerHash: common.HexToHash("367967247499343401261d718ed5aa4c9486583e4d89251afce47f4a33c33362"), 187 wantSignErr: ErrInvalidChainId, 188 }, 189 } 190 191 for i, test := range tests { 192 sigHash := test.signer.Hash(test.tx) 193 if sigHash != test.wantSignerHash { 194 t.Errorf("test %d: wrong sig hash: got %x, want %x", i, sigHash, test.wantSignerHash) 195 } 196 sender, err := Sender(test.signer, test.tx) 197 if err != test.wantSenderErr { 198 t.Errorf("test %d: wrong Sender error %q", i, err) 199 } 200 if err == nil && sender != keyAddr { 201 t.Errorf("test %d: wrong sender address %x", i, sender) 202 } 203 signedTx, err := SignTx(test.tx, test.signer, key) 204 if err != test.wantSignErr { 205 t.Fatalf("test %d: wrong SignTx error %q", i, err) 206 } 207 if signedTx != nil { 208 if signedTx.Hash() != test.wantHash { 209 t.Errorf("test %d: wrong tx hash after signing: got %x, want %x", i, signedTx.Hash(), test.wantHash) 210 } 211 } 212 } 213 } 214 215 func TestHomesteadSigner(t *testing.T) { 216 rlpTx := common.Hex2Bytes("f87e8085174876e800830186a08080ad601f80600e600039806000f350fe60003681823780368234f58015156014578182fd5b80825250506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222") 217 218 tx, err := decodeTx(rlpTx) 219 assert.NoError(t, err) 220 221 addr, err := EIP155Signer{}.Sender(tx) 222 assert.NoError(t, err) 223 assert.Equal(t, "0x4c8D290a1B368ac4728d83a9e8321fC3af2b39b1", addr.String()) 224 } 225 226 // This test checks signature operations on dynamic fee transactions. 227 func TestLondonSigner(t *testing.T) { 228 var ( 229 key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 230 keyAddr = crypto.PubkeyToAddress(key.PublicKey) 231 signer1 = NewLondonSigner(big.NewInt(1)) 232 signer2 = NewLondonSigner(big.NewInt(2)) 233 tx0 = NewTx(&TxInternalDataEthereumDynamicFee{AccountNonce: 1, ChainID: new(big.Int)}) 234 tx1 = NewTx(&TxInternalDataEthereumDynamicFee{ChainID: big.NewInt(1), AccountNonce: 1, V: new(big.Int), R: new(big.Int), S: new(big.Int)}) 235 tx2, _ = SignTx(NewTx(&TxInternalDataEthereumDynamicFee{ChainID: big.NewInt(2), AccountNonce: 1}), signer2, key) 236 ) 237 238 tests := []struct { 239 tx *Transaction 240 signer Signer 241 wantSignerHash common.Hash 242 wantSenderErr error 243 wantSignErr error 244 wantHash common.Hash // after signing 245 }{ 246 { 247 tx: tx0, 248 signer: signer1, 249 wantSignerHash: common.HexToHash("b6afee4d44e0392fb5d3204b350596d6677440bced7ebd998db73c9671527c57"), 250 wantSenderErr: ErrInvalidChainId, 251 wantHash: common.HexToHash("a2c6373b7eed946fd4165a0d8503aa26afc8e99f09e2be58b332fbbedc279f7a"), 252 }, 253 { 254 tx: tx1, 255 signer: signer1, 256 wantSenderErr: ErrInvalidSig, 257 wantSignerHash: common.HexToHash("b6afee4d44e0392fb5d3204b350596d6677440bced7ebd998db73c9671527c57"), 258 wantHash: common.HexToHash("a2c6373b7eed946fd4165a0d8503aa26afc8e99f09e2be58b332fbbedc279f7a"), 259 }, 260 { 261 // This checks what happens when trying to sign an unsigned tx for the wrong chain. 262 tx: tx1, 263 signer: signer2, 264 wantSenderErr: ErrInvalidChainId, 265 wantSignerHash: common.HexToHash("b6afee4d44e0392fb5d3204b350596d6677440bced7ebd998db73c9671527c57"), 266 wantSignErr: ErrInvalidChainId, 267 }, 268 { 269 // This checks what happens when trying to re-sign a signed tx for the wrong chain. 270 tx: tx2, 271 signer: signer1, 272 wantSenderErr: ErrInvalidChainId, 273 wantSignerHash: common.HexToHash("b0759fc55582f3e60ded82843dcc17733d8c65f543d2cf2613a47a5c6ac9fc48"), 274 wantSignErr: ErrInvalidChainId, 275 }, 276 } 277 278 for i, test := range tests { 279 sigHash := test.signer.Hash(test.tx) 280 if sigHash != test.wantSignerHash { 281 t.Errorf("test %d: wrong sig hash: got %x, want %x", i, sigHash, test.wantSignerHash) 282 } 283 sender, err := Sender(test.signer, test.tx) 284 if err != test.wantSenderErr { 285 t.Errorf("test %d: wrong Sender error %q", i, err) 286 } 287 if err == nil && sender != keyAddr { 288 t.Errorf("test %d: wrong sender address %x", i, sender) 289 } 290 signedTx, err := SignTx(test.tx, test.signer, key) 291 if err != test.wantSignErr { 292 t.Fatalf("test %d: wrong SignTx error %q", i, err) 293 } 294 if signedTx != nil { 295 if signedTx.Hash() != test.wantHash { 296 t.Errorf("test %d: wrong tx hash after signing: got %x, want %x", i, signedTx.Hash(), test.wantHash) 297 } 298 } 299 } 300 } 301 302 func TestTransactionEncode(t *testing.T) { 303 txb, err := rlp.EncodeToBytes(rightvrsTx) 304 if err != nil { 305 t.Fatalf("encode error: %v", err) 306 } 307 should := common.FromHex("f86103018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a82554426a098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3") 308 if !bytes.Equal(txb, should) { 309 t.Errorf("encoded RLP mismatch, ɡot %x", txb) 310 } 311 } 312 313 func TestEIP2718TransactionEncode(t *testing.T) { 314 // RLP representation 315 { 316 have, err := rlp.EncodeToBytes(signedEip2718Tx) 317 if err != nil { 318 t.Fatalf("encode error: %v", err) 319 } 320 want := common.FromHex("7801f8630103018261a894b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a825544c001a0c9519f4f2b30335884581971573fadf60c6204f59a911df35ee8a540456b2660a032f1e8e2c5dd761f9e4f88f41c8310aeaba26a8bfcdacfedfa12ec3862d37521") 321 if !bytes.Equal(have, want) { 322 t.Errorf("encoded RLP mismatch, got %x", have) 323 } 324 } 325 } 326 327 func TestEIP1559TransactionEncode(t *testing.T) { 328 // RLP representation 329 { 330 have, err := rlp.EncodeToBytes(signedEip1559Tx) 331 if err != nil { 332 t.Fatalf("encode error: %v", err) 333 } 334 want := common.FromHex("7802f89d010301018261a894b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a825544f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000001a0c9519f4f2b30335884581971573fadf60c6204f59a911df35ee8a540456b2660a032f1e8e2c5dd761f9e4f88f41c8310aeaba26a8bfcdacfedfa12ec3862d37521") 335 if !bytes.Equal(have, want) { 336 t.Errorf("encoded RLP mismatch, got %x", have) 337 } 338 } 339 } 340 341 func TestEffectiveGasPrice(t *testing.T) { 342 gasPrice := big.NewInt(1000) 343 gasFeeCap, gasTipCap := big.NewInt(4000), big.NewInt(1000) 344 345 legacyTx := NewTx(&TxInternalDataLegacy{Price: gasPrice}) 346 dynamicTx := NewTx(&TxInternalDataEthereumDynamicFee{GasFeeCap: gasFeeCap, GasTipCap: gasTipCap}) 347 348 header := new(Header) 349 350 have := legacyTx.EffectiveGasPrice(header) 351 want := gasPrice 352 assert.Equal(t, want, have) 353 354 have = dynamicTx.EffectiveGasPrice(header) 355 te := dynamicTx.GetTxInternalData().(TxInternalDataBaseFee) 356 want = te.GetGasFeeCap() 357 assert.Equal(t, want, have) 358 359 header.BaseFee = big.NewInt(2000) 360 have = legacyTx.EffectiveGasPrice(header) 361 want = header.BaseFee 362 assert.Equal(t, want, have) 363 364 have = dynamicTx.EffectiveGasPrice(header) 365 want = header.BaseFee 366 assert.Equal(t, want, have) 367 368 header.BaseFee = big.NewInt(0) 369 have = legacyTx.EffectiveGasPrice(header) 370 want = header.BaseFee 371 assert.Equal(t, want, have) 372 373 have = dynamicTx.EffectiveGasPrice(header) 374 want = header.BaseFee 375 assert.Equal(t, want, have) 376 } 377 378 func TestEffectiveGasTip(t *testing.T) { 379 legacyTx := NewTx(&TxInternalDataLegacy{Price: big.NewInt(1000)}) 380 dynamicTx := NewTx(&TxInternalDataEthereumDynamicFee{GasFeeCap: big.NewInt(4000), GasTipCap: big.NewInt(1000)}) 381 382 // before magma hardfork 383 baseFee := big.NewInt(2000) 384 have := legacyTx.EffectiveGasTip(baseFee) 385 want := big.NewInt(1000) 386 assert.Equal(t, want, have) 387 388 baseFee = big.NewInt(2000) 389 have = dynamicTx.EffectiveGasTip(baseFee) 390 want = big.NewInt(1000) 391 assert.Equal(t, want, have) 392 393 // before magma hardfork 394 baseFee = big.NewInt(0) 395 have = legacyTx.EffectiveGasTip(baseFee) 396 want = big.NewInt(1000) 397 assert.Equal(t, want, have) 398 399 have = dynamicTx.EffectiveGasTip(baseFee) 400 want = big.NewInt(1000) 401 assert.Equal(t, want, have) 402 403 a := new(big.Int) 404 assert.Equal(t, 0, a.BitLen()) 405 } 406 407 func decodeTx(data []byte) (*Transaction, error) { 408 var tx Transaction 409 t, err := &tx, rlp.Decode(bytes.NewReader(data), &tx) 410 411 return t, err 412 } 413 414 func defaultTestKey() (*ecdsa.PrivateKey, common.Address) { 415 key, _ := crypto.HexToECDSA("45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8") 416 addr := crypto.PubkeyToAddress(key.PublicKey) 417 return key, addr 418 } 419 420 func TestRecipientEmpty(t *testing.T) { 421 _, addr := defaultTestKey() 422 tx, err := decodeTx(common.Hex2Bytes("f84980808080800126a0f18ba0124c1ed46fef6673ff5f614bafbb33a23ad92874bfa3cb3abad56d9a72a046690eb704a07384224d12e991da61faceefede59c6741d85e7d72e097855eaf")) 423 if err != nil { 424 t.Fatal(err) 425 } 426 427 signer := LatestSignerForChainID(common.Big1) 428 429 from, err := Sender(signer, tx) 430 if err != nil { 431 t.Fatal(err) 432 } 433 if addr != from { 434 t.Error("derived address doesn't match") 435 } 436 } 437 438 func TestRecipientNormal(t *testing.T) { 439 _, addr := defaultTestKey() 440 441 tx, err := decodeTx(common.Hex2Bytes("f85d808080940000000000000000000000000000000000000000800126a0c1f2953a2277033c693f3d352b740479788672ba21e76d567557aa069b7e5061a06e798331dbd58c7438fe0e0a64b3b17c8378c726da3613abae8783b5dccc9944")) 442 if err != nil { 443 t.Fatal(err) 444 } 445 446 signer := LatestSignerForChainID(common.Big1) 447 448 from, err := Sender(signer, tx) 449 if err != nil { 450 t.Fatal(err) 451 } 452 453 if addr != from { 454 t.Fatal("derived address doesn't match") 455 } 456 } 457 458 // Tests that transactions can be correctly sorted according to their price in 459 // decreasing order, but at the same time with increasing nonces when issued by 460 // the same account. 461 func TestTransactionPriceNonceSort(t *testing.T) { 462 // Generate a batch of accounts to start with 463 keys := make([]*ecdsa.PrivateKey, 25) 464 for i := 0; i < len(keys); i++ { 465 keys[i], _ = crypto.GenerateKey() 466 } 467 468 signer := LatestSignerForChainID(common.Big1) 469 // Generate a batch of transactions with overlapping values, but shifted nonces 470 groups := map[common.Address]Transactions{} 471 for start, key := range keys { 472 addr := crypto.PubkeyToAddress(key.PublicKey) 473 for i := 0; i < 25; i++ { 474 tx, _ := SignTx(NewTransaction(uint64(start+i), common.Address{}, big.NewInt(100), 100, big.NewInt(int64(start+i)), nil), signer, key) 475 groups[addr] = append(groups[addr], tx) 476 } 477 } 478 // Sort the transactions and cross check the nonce ordering 479 txset := NewTransactionsByTimeAndNonce(signer, groups) 480 481 txs := Transactions{} 482 for tx := txset.Peek(); tx != nil; tx = txset.Peek() { 483 txs = append(txs, tx) 484 txset.Shift() 485 } 486 if len(txs) != 25*25 { 487 t.Errorf("expected %d transactions, found %d", 25*25, len(txs)) 488 } 489 for i, txi := range txs { 490 fromi, _ := Sender(signer, txi) 491 492 // Make sure the nonce order is valid 493 for j, txj := range txs[i+1:] { 494 fromj, _ := Sender(signer, txj) 495 496 if fromi == fromj && txi.Nonce() > txj.Nonce() { 497 t.Errorf("invalid nonce ordering: tx #%d (A=%x N=%v) < tx #%d (A=%x N=%v)", i, fromi[:4], txi.Nonce(), i+j, fromj[:4], txj.Nonce()) 498 } 499 } 500 501 // If the next tx has different from account, the price must be lower than the current one 502 if i+1 < len(txs) { 503 next := txs[i+1] 504 fromNext, _ := Sender(signer, next) 505 if fromi != fromNext && txi.GasPrice().Cmp(next.GasPrice()) < 0 { 506 t.Errorf("invalid ɡasprice ordering: tx #%d (A=%x P=%v) < tx #%d (A=%x P=%v)", i, fromi[:4], txi.GasPrice(), i+1, fromNext[:4], next.GasPrice()) 507 } 508 } 509 } 510 } 511 512 func TestGasOverflow(t *testing.T) { 513 // AccountCreation 514 // calculate gas for account creation 515 numKeys := new(big.Int).SetUint64(accountkey.MaxNumKeysForMultiSig) 516 gasPerKey := new(big.Int).SetUint64(params.TxAccountCreationGasPerKey) 517 defaultGas := new(big.Int).SetUint64(params.TxAccountCreationGasDefault) 518 txGas := new(big.Int).SetUint64(params.TxGasAccountCreation) 519 totalGas := new(big.Int).Add(txGas, new(big.Int).Add(defaultGas, new(big.Int).Mul(numKeys, gasPerKey))) 520 assert.Equal(t, true, totalGas.BitLen() <= 64) 521 522 // ValueTransfer 523 // calculate gas for validation of multisig accounts. 524 gasPerKey = new(big.Int).SetUint64(params.TxValidationGasPerKey) 525 defaultGas = new(big.Int).SetUint64(params.TxValidationGasDefault) 526 txGas = new(big.Int).SetUint64(params.TxGas) 527 totalGas = new(big.Int).Add(txGas, new(big.Int).Add(defaultGas, new(big.Int).Mul(numKeys, gasPerKey))) 528 assert.Equal(t, true, totalGas.BitLen() <= 64) 529 530 // TODO-Klaytn-Gas: Need to find a way of checking integer overflow for smart contract execution. 531 } 532 533 // TODO-Klaytn-FailedTest This test is failed in Klaytn 534 /* 535 // TestTransactionJSON tests serializing/de-serializing to/from JSON. 536 func TestTransactionJSON(t *testing.T) { 537 key, err := crypto.GenerateKey() 538 if err != nil { 539 t.Fatalf("could not generate key: %v", err) 540 } 541 signer := NewEIP155Signer(common.Big1) 542 543 transactions := make([]*Transaction, 0, 50) 544 for i := uint64(0); i < 25; i++ { 545 var tx *Transaction 546 switch i % 2 { 547 case 0: 548 tx = NewTransaction(i, common.Address{1}, common.Big0, 1, common.Big2, []byte("abcdef")) 549 case 1: 550 tx = NewContractCreation(i, common.Big0, 1, common.Big2, []byte("abcdef")) 551 } 552 transactions = append(transactions, tx) 553 554 signedTx, err := SignTx(tx, signer, key) 555 if err != nil { 556 t.Fatalf("could not sign transaction: %v", err) 557 } 558 559 transactions = append(transactions, signedTx) 560 } 561 562 for _, tx := range transactions { 563 data, err := json.Marshal(tx) 564 if err != nil { 565 t.Fatalf("json.Marshal failed: %v", err) 566 } 567 568 var parsedTx *Transaction 569 if err := json.Unmarshal(data, &parsedTx); err != nil { 570 t.Fatalf("json.Unmarshal failed: %v", err) 571 } 572 573 // compare nonce, price, gaslimit, recipient, amount, payload, V, R, S 574 if tx.Hash() != parsedTx.Hash() { 575 t.Errorf("parsed tx differs from original tx, want %v, ɡot %v", tx, parsedTx) 576 } 577 if tx.ChainId().Cmp(parsedTx.ChainId()) != 0 { 578 t.Errorf("invalid chain id, want %d, ɡot %d", tx.ChainId(), parsedTx.ChainId()) 579 } 580 } 581 } 582 */ 583 584 func TestIntrinsicGas(t *testing.T) { 585 // testData contains two kind of members 586 // inputString - test input data 587 // expectGas - expect gas according to the specific condition. 588 // it differs depending on whether the contract is created or not, 589 // or whether it has passed through the Istanbul compatible block. 590 testData := []struct { 591 inputString string 592 expectGas1 uint64 // contractCreate - false, isIstanbul - false 593 expectGas2 uint64 // contractCreate - false, isIstanbul - true 594 expectGas3 uint64 // contractCreate - true, isIstanbul - false 595 expectGas4 uint64 // contractCreate - true, isIstanbul - true 596 }{ 597 {"0000", 21008, 21200, 53008, 53200}, 598 {"1000", 21072, 21200, 53072, 53200}, 599 {"0100", 21072, 21200, 53072, 53200}, 600 {"ff3d", 21136, 21200, 53136, 53200}, 601 {"0000a6bc", 21144, 21400, 53144, 53400}, 602 {"fd00fd00", 21144, 21400, 53144, 53400}, 603 {"", 21000, 21000, 53000, 53000}, 604 } 605 for _, tc := range testData { 606 var ( 607 data []byte // input data entered through the tx argument 608 gas uint64 // the gas varies depending on what comes in as a condition(contractCreate & IsIstanbulForkEnabled) 609 err error // in this unittest, every testcase returns nil error. 610 ) 611 612 data, err = hex.DecodeString(tc.inputString) // decode input string to hex data 613 assert.Equal(t, nil, err) 614 615 gas, err = IntrinsicGas(data, nil, false, params.Rules{IsIstanbul: false}) 616 assert.Equal(t, tc.expectGas1, gas) 617 assert.Equal(t, nil, err) 618 619 gas, err = IntrinsicGas(data, nil, false, params.Rules{IsIstanbul: true}) 620 assert.Equal(t, tc.expectGas2, gas) 621 assert.Equal(t, nil, err) 622 623 gas, err = IntrinsicGas(data, nil, true, params.Rules{IsIstanbul: false}) 624 assert.Equal(t, tc.expectGas3, gas) 625 assert.Equal(t, nil, err) 626 627 gas, err = IntrinsicGas(data, nil, true, params.Rules{IsIstanbul: true}) 628 assert.Equal(t, tc.expectGas4, gas) 629 assert.Equal(t, nil, err) 630 } 631 } 632 633 // Tests that if multiple transactions have the same price, the ones seen earlier 634 // are prioritized to avoid network spam attacks aiming for a specific ordering. 635 func TestTransactionTimeSort(t *testing.T) { 636 // Generate a batch of accounts to start with 637 keys := make([]*ecdsa.PrivateKey, 5) 638 for i := 0; i < len(keys); i++ { 639 keys[i], _ = crypto.GenerateKey() 640 } 641 signer := LatestSignerForChainID(big.NewInt(1)) 642 643 // Generate a batch of transactions with overlapping prices, but different creation times 644 groups := map[common.Address]Transactions{} 645 for start, key := range keys { 646 addr := crypto.PubkeyToAddress(key.PublicKey) 647 648 tx, _ := SignTx(NewTransaction(0, common.Address{}, big.NewInt(100), 100, big.NewInt(1), nil), signer, key) 649 tx.time = time.Unix(0, int64(len(keys)-start)) 650 651 groups[addr] = append(groups[addr], tx) 652 } 653 // Sort the transactions and cross check the nonce ordering 654 txset := NewTransactionsByTimeAndNonce(signer, groups) 655 656 txs := Transactions{} 657 for tx := txset.Peek(); tx != nil; tx = txset.Peek() { 658 txs = append(txs, tx) 659 txset.Shift() 660 } 661 if len(txs) != len(keys) { 662 t.Errorf("expected %d transactions, found %d", len(keys), len(txs)) 663 } 664 for i, txi := range txs { 665 fromi, _ := Sender(signer, txi) 666 if i+1 < len(txs) { 667 next := txs[i+1] 668 fromNext, _ := Sender(signer, next) 669 670 if txi.GasPrice().Cmp(next.GasPrice()) < 0 { 671 t.Errorf("invalid gasprice ordering: tx #%d (A=%x P=%v) < tx #%d (A=%x P=%v)", i, fromi[:4], txi.GasPrice(), i+1, fromNext[:4], next.GasPrice()) 672 } 673 // Make sure time order is ascending if the txs have the same gas price 674 if txi.GasPrice().Cmp(next.GasPrice()) == 0 && txi.time.After(next.time) { 675 t.Errorf("invalid received time ordering: tx #%d (A=%x T=%v) > tx #%d (A=%x T=%v)", i, fromi[:4], txi.time, i+1, fromNext[:4], next.time) 676 } 677 } 678 } 679 } 680 681 // TestTransactionTimeSortDifferentGasPrice tests that although multiple transactions have the different price, the ones seen earlier 682 // are prioritized to avoid network spam attacks aiming for a specific ordering. 683 func TestTransactionTimeSortDifferentGasPrice(t *testing.T) { 684 // Generate a batch of accounts to start with 685 keys := make([]*ecdsa.PrivateKey, 5) 686 for i := 0; i < len(keys); i++ { 687 keys[i], _ = crypto.GenerateKey() 688 } 689 signer := LatestSignerForChainID(big.NewInt(1)) 690 691 // Generate a batch of transactions with overlapping prices, but different creation times 692 groups := map[common.Address]Transactions{} 693 gasPrice := big.NewInt(1) 694 for start, key := range keys { 695 addr := crypto.PubkeyToAddress(key.PublicKey) 696 697 tx, _ := SignTx(NewTransaction(0, common.Address{}, big.NewInt(100), 100, gasPrice, nil), signer, key) 698 tx.time = time.Unix(0, int64(len(keys)-start)) 699 700 groups[addr] = append(groups[addr], tx) 701 702 gasPrice = gasPrice.Add(gasPrice, big.NewInt(1)) 703 } 704 // Sort the transactions and cross check the nonce ordering 705 txset := NewTransactionsByTimeAndNonce(signer, groups) 706 707 txs := Transactions{} 708 for tx := txset.Peek(); tx != nil; tx = txset.Peek() { 709 txs = append(txs, tx) 710 txset.Shift() 711 } 712 if len(txs) != len(keys) { 713 t.Errorf("expected %d transactions, found %d", len(keys), len(txs)) 714 } 715 for i, tx := range txs { 716 from, _ := Sender(signer, tx) 717 if i+1 < len(txs) { 718 next := txs[i+1] 719 fromNext, _ := Sender(signer, next) 720 721 // Make sure time order is ascending. 722 if tx.time.After(next.time) { 723 t.Errorf("invalid received time ordering: tx #%d (A=%x T=%v) > tx #%d (A=%x T=%v)", i, from[:4], tx.time, i+1, fromNext[:4], next.time) 724 } 725 } 726 } 727 } 728 729 // TestTransactionCoding tests serializing/de-serializing to/from rlp and JSON. 730 func TestTransactionCoding(t *testing.T) { 731 key, err := crypto.GenerateKey() 732 if err != nil { 733 t.Fatalf("could not generate key: %v", err) 734 } 735 var ( 736 signer = LatestSignerForChainID(common.Big1) 737 addr = common.HexToAddress("0x0000000000000000000000000000000000000001") 738 recipient = common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87") 739 accesses = AccessList{{Address: addr, StorageKeys: []common.Hash{{0}}}} 740 ) 741 for i := uint64(0); i < 500; i++ { 742 var txData TxInternalData 743 switch i % 5 { 744 case 0: 745 // Legacy tx. 746 txData = &TxInternalDataLegacy{ 747 AccountNonce: i, 748 Recipient: &recipient, 749 GasLimit: 1, 750 Price: big.NewInt(2), 751 Payload: []byte("abcdef"), 752 } 753 case 1: 754 // Legacy tx contract creation. 755 txData = &TxInternalDataLegacy{ 756 AccountNonce: i, 757 GasLimit: 1, 758 Price: big.NewInt(2), 759 Payload: []byte("abcdef"), 760 } 761 case 2: 762 // Tx with non-zero access list. 763 txData = &TxInternalDataEthereumAccessList{ 764 ChainID: big.NewInt(1), 765 AccountNonce: i, 766 Recipient: &recipient, 767 GasLimit: 123457, 768 Price: big.NewInt(10), 769 AccessList: accesses, 770 Payload: []byte("abcdef"), 771 } 772 case 3: 773 // Tx with empty access list. 774 txData = &TxInternalDataEthereumAccessList{ 775 ChainID: big.NewInt(1), 776 AccountNonce: i, 777 Recipient: &recipient, 778 GasLimit: 123457, 779 Price: big.NewInt(10), 780 Payload: []byte("abcdef"), 781 } 782 case 4: 783 // Contract creation with access list. 784 txData = &TxInternalDataEthereumAccessList{ 785 ChainID: big.NewInt(1), 786 AccountNonce: i, 787 GasLimit: 123457, 788 Price: big.NewInt(10), 789 AccessList: accesses, 790 } 791 case 5: 792 // Tx with non-zero access list. 793 txData = &TxInternalDataEthereumDynamicFee{ 794 ChainID: big.NewInt(1), 795 AccountNonce: i, 796 Recipient: &recipient, 797 GasLimit: 123457, 798 GasFeeCap: big.NewInt(10), 799 GasTipCap: big.NewInt(10), 800 AccessList: accesses, 801 Payload: []byte("abcdef"), 802 } 803 case 6: 804 // Tx with dynamic fee. 805 txData = &TxInternalDataEthereumDynamicFee{ 806 ChainID: big.NewInt(1), 807 AccountNonce: i, 808 Recipient: &recipient, 809 GasLimit: 123457, 810 GasFeeCap: big.NewInt(10), 811 GasTipCap: big.NewInt(10), 812 Payload: []byte("abcdef"), 813 } 814 case 7: 815 // Contract creation with dynamic fee tx. 816 txData = &TxInternalDataEthereumDynamicFee{ 817 ChainID: big.NewInt(1), 818 AccountNonce: i, 819 GasLimit: 123457, 820 GasFeeCap: big.NewInt(10), 821 GasTipCap: big.NewInt(10), 822 AccessList: accesses, 823 } 824 } 825 826 transaction := Transaction{data: txData} 827 tx, err := SignTx(&transaction, signer, key) 828 if err != nil { 829 t.Fatalf("could not sign transaction: %v", err) 830 } 831 // RLP 832 parsedTx, err := encodeDecodeBinary(tx) 833 if err != nil { 834 t.Fatal(err) 835 } 836 assertEqual(parsedTx, tx) 837 838 // JSON 839 parsedTx, err = encodeDecodeJSON(tx) 840 if err != nil { 841 t.Fatal(err) 842 } 843 assertEqual(parsedTx, tx) 844 } 845 } 846 847 func encodeDecodeJSON(tx *Transaction) (*Transaction, error) { 848 data, err := json.Marshal(tx) 849 if err != nil { 850 return nil, fmt.Errorf("json encoding failed: %v", err) 851 } 852 parsedTx := &Transaction{} 853 if err := json.Unmarshal(data, &parsedTx); err != nil { 854 return nil, fmt.Errorf("json decoding failed: %v", err) 855 } 856 return parsedTx, nil 857 } 858 859 func encodeDecodeBinary(tx *Transaction) (*Transaction, error) { 860 data, err := tx.MarshalBinary() 861 if err != nil { 862 return nil, fmt.Errorf("rlp encoding failed: %v", err) 863 } 864 parsedTx := &Transaction{} 865 if err := parsedTx.UnmarshalBinary(data); err != nil { 866 return nil, fmt.Errorf("rlp decoding failed: %v", err) 867 } 868 return parsedTx, nil 869 } 870 871 func assertEqual(orig *Transaction, cpy *Transaction) error { 872 // compare nonce, price, gaslimit, recipient, amount, payload, V, R, S 873 if want, got := orig.Hash(), cpy.Hash(); want != got { 874 return fmt.Errorf("parsed tx differs from original tx, want %v, got %v", want, got) 875 } 876 if want, got := orig.ChainId(), cpy.ChainId(); want.Cmp(got) != 0 { 877 return fmt.Errorf("invalid chain id, want %d, got %d", want, got) 878 } 879 880 if orig.Type().IsEthTypedTransaction() && cpy.Type().IsEthTypedTransaction() { 881 tOrig := orig.data.(TxInternalDataEthTyped) 882 tCpy := cpy.data.(TxInternalDataEthTyped) 883 884 if !reflect.DeepEqual(tOrig.GetAccessList(), tCpy.GetAccessList()) { 885 return fmt.Errorf("access list wrong!") 886 } 887 } 888 889 return nil 890 } 891 892 func TestIsSorted(t *testing.T) { 893 signer := LatestSignerForChainID(big.NewInt(1)) 894 895 key, _ := crypto.GenerateKey() 896 batches := make(Transactions, 10) 897 898 for i := 0; i < 10; i++ { 899 batches[i], _ = SignTx(NewTransaction(uint64(i), common.Address{}, big.NewInt(100), 100, big.NewInt(int64(i)), nil), signer, key) 900 } 901 902 // Shuffle transactions. 903 rand.Seed(time.Now().Unix()) 904 rand.Shuffle(len(batches), func(i, j int) { 905 batches[i], batches[j] = batches[j], batches[i] 906 }) 907 908 sort.Sort(TxByPriceAndTime(batches)) 909 assert.True(t, sort.IsSorted(TxByPriceAndTime(batches))) 910 } 911 912 func TestFilterTransactionWithBaseFee(t *testing.T) { 913 signer := LatestSignerForChainID(big.NewInt(1)) 914 915 pending := make(map[common.Address]Transactions) 916 keys := make([]*ecdsa.PrivateKey, 3) 917 918 for i := 0; i < len(keys); i++ { 919 keys[i], _ = crypto.GenerateKey() 920 } 921 922 from1 := crypto.PubkeyToAddress(keys[0].PublicKey) 923 txs1 := make(Transactions, 3) 924 txs1[0], _ = SignTx(NewTransaction(uint64(0), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[0]) 925 txs1[1], _ = SignTx(NewTransaction(uint64(1), common.Address{}, big.NewInt(100), 100, big.NewInt(40), nil), signer, keys[0]) 926 txs1[2], _ = SignTx(NewTransaction(uint64(2), common.Address{}, big.NewInt(100), 100, big.NewInt(50), nil), signer, keys[0]) 927 pending[from1] = txs1 928 929 from2 := crypto.PubkeyToAddress(keys[1].PublicKey) 930 txs2 := make(Transactions, 4) 931 txs2[0], _ = SignTx(NewTransaction(uint64(0), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[1]) 932 txs2[1], _ = SignTx(NewTransaction(uint64(1), common.Address{}, big.NewInt(100), 100, big.NewInt(20), nil), signer, keys[1]) 933 txs2[2], _ = SignTx(NewTransaction(uint64(2), common.Address{}, big.NewInt(100), 100, big.NewInt(40), nil), signer, keys[1]) 934 txs2[3], _ = SignTx(NewTransaction(uint64(3), common.Address{}, big.NewInt(100), 100, big.NewInt(40), nil), signer, keys[1]) 935 pending[from2] = txs2 936 937 from3 := crypto.PubkeyToAddress(keys[2].PublicKey) 938 txs3 := make(Transactions, 5) 939 txs3[0], _ = SignTx(NewTransaction(uint64(0), common.Address{}, big.NewInt(100), 100, big.NewInt(10), nil), signer, keys[2]) 940 txs3[1], _ = SignTx(NewTransaction(uint64(1), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[2]) 941 txs3[2], _ = SignTx(NewTransaction(uint64(2), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[2]) 942 txs3[3], _ = SignTx(NewTransaction(uint64(3), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[2]) 943 txs3[4], _ = SignTx(NewTransaction(uint64(4), common.Address{}, big.NewInt(100), 100, big.NewInt(30), nil), signer, keys[2]) 944 pending[from3] = txs3 945 946 baseFee := big.NewInt(30) 947 pending = FilterTransactionWithBaseFee(pending, baseFee) 948 949 assert.Equal(t, len(pending[from1]), 3) 950 for i := 0; i < len(pending[from1]); i++ { 951 assert.Equal(t, txs1[i], pending[from1][i]) 952 } 953 954 assert.Equal(t, len(pending[from2]), 1) 955 for i := 0; i < len(pending[from2]); i++ { 956 assert.Equal(t, txs2[i], pending[from2][i]) 957 } 958 959 assert.Equal(t, len(pending[from3]), 0) 960 } 961 962 func BenchmarkTxSortByTime30000(b *testing.B) { benchmarkTxSortByTime(b, 30000) } 963 func BenchmarkTxSortByTime20000(b *testing.B) { benchmarkTxSortByTime(b, 20000) } 964 func benchmarkTxSortByTime(b *testing.B, size int) { 965 signer := LatestSignerForChainID(big.NewInt(1)) 966 967 key, _ := crypto.GenerateKey() 968 batches := make(Transactions, size) 969 970 for i := 0; i < size; i++ { 971 batches[i], _ = SignTx(NewTransaction(uint64(i), common.Address{}, big.NewInt(100), 100, big.NewInt(int64(i)), nil), signer, key) 972 } 973 974 // Shuffle transactions. 975 rand.Seed(time.Now().Unix()) 976 rand.Shuffle(len(batches), func(i, j int) { 977 batches[i], batches[j] = batches[j], batches[i] 978 }) 979 980 // Benchmark importing the transactions into the queue 981 b.ResetTimer() 982 983 for i := 0; i < b.N; i++ { 984 sort.Sort(TxByPriceAndTime(batches)) 985 } 986 }