• Mark Tyneway's avatar
    l2geth: update timestamp logic · 57742a04
    Mark Tyneway authored
    This commit updates the timestamp updating logic
    such that `time.Now` is used instead of relying on
    L1 timestamps. This gives a higher fidelity for the
    `TIMESTAMP` opcode as well as makes the time on L2
    be closer to the time on L1.
    
    L1 to L2 transactions no longer have the property of
    having the same timestamp on L2 as the timestamp
    of the L1 block they were included in.
    
    This should be able to be turned on without needing
    hardfork logic as replicas should always accept the
    timestamp that the sequencer sets. The sequencer is
    a trusted entity in the existing implementation and
    it is expected that the sequencer will become more
    trustless in future iterations of the protocol.
    
    This change is added to improve both UX and devex.
    Users are confused by the timestamps on Etherscan
    being ~15 minutes behind. This is due to the timestamps
    being set based on L1 block numbers, and the system
    only pulls L1 data once a secure amount of PoW
    is placed on top. Developers would like the timestamps
    to have a higher fidelity and be closer to the timestamps
    on L1.
    57742a04
sync_service_test.go 30.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
package rollup

import (
	"context"
	"crypto/rand"
	"errors"
	"fmt"
	"math/big"
	"reflect"
	"sync"
	"testing"
	"time"

	"github.com/ethereum-optimism/optimism/l2geth/common"
	"github.com/ethereum-optimism/optimism/l2geth/consensus/ethash"
	"github.com/ethereum-optimism/optimism/l2geth/core"
	"github.com/ethereum-optimism/optimism/l2geth/core/rawdb"
	"github.com/ethereum-optimism/optimism/l2geth/core/types"
	"github.com/ethereum-optimism/optimism/l2geth/core/vm"
	"github.com/ethereum-optimism/optimism/l2geth/crypto"
	"github.com/ethereum-optimism/optimism/l2geth/eth/gasprice"
	"github.com/ethereum-optimism/optimism/l2geth/ethdb"
	"github.com/ethereum-optimism/optimism/l2geth/event"
	"github.com/ethereum-optimism/optimism/l2geth/params"
	"github.com/ethereum-optimism/optimism/l2geth/rollup/rcfg"
)

// Test that the timestamps are updated correctly.
// This impacts execution, for `block.timestamp`
func TestSyncServiceTimestampUpdate(t *testing.T) {
	service, txCh, _, err := newTestSyncService(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Get the timestamp from the sync service
	// It should be initialized to 0
	ts := service.GetLatestL1Timestamp()
	if ts != 0 {
		t.Fatalf("Unexpected timestamp: %d", ts)
	}

	// Create a mock transaction and assert that its timestamp
	// a value. This tests the case that the timestamp does
	// not get malleated when it is set to a non zero value
	timestamp := uint64(1)
	tx1 := setMockTxL1Timestamp(mockTx(), timestamp)
	if tx1.GetMeta().L1Timestamp != timestamp {
		t.Fatalf("Expecting mock timestamp to be %d", timestamp)
	}
	if tx1.GetMeta().QueueOrigin != types.QueueOriginSequencer {
		t.Fatalf("Expecting mock queue origin to be queue origin sequencer")
	}

	go func() {
		err = service.applyTransactionToTip(tx1)
	}()
	event1 := <-txCh

	// Ensure that the timestamp isn't malleated
	if event1.Txs[0].GetMeta().L1Timestamp != timestamp {
		t.Fatalf("Timestamp was malleated: %d", event1.Txs[0].GetMeta().L1Timestamp)
	}
	// Ensure that the timestamp in the sync service was updated
	if service.GetLatestL1Timestamp() != timestamp {
		t.Fatal("timestamp updated in sync service")
	}

	// Now test the case for when a transaction is malleated.
	// If the timestamp is 0, then it should be malleated and set
	// equal to whatever the latestL1Timestamp is
	tx2 := mockTx()
	if tx2.GetMeta().L1Timestamp != 0 {
		t.Fatal("Expecting mock timestamp to be 0")
	}
	go func() {
		err = service.applyTransactionToTip(tx2)
	}()
	event2 := <-txCh

	// Ensure that the sync service timestamp is updated
	if service.GetLatestL1Timestamp() == 0 {
		t.Fatal("timestamp not updated")
	}
	// Ensure that the timestamp is malleated to be equal to what the sync
	// service has as the latest timestamp
	if event2.Txs[0].GetMeta().L1Timestamp != service.GetLatestL1Timestamp() {
		t.Fatal("unexpected timestamp update")
	}

	// L1ToL2 transactions should have their timestamp malleated
	// Be sure to set the timestamp to a non zero value so that
	// its specifically testing the fact its a deposit tx
	tx3 := setMockQueueOrigin(setMockTxL1Timestamp(mockTx(), 100), types.QueueOriginL1ToL2)
	// Get a reference to the timestamp before transaction execution
	ts3 := service.GetLatestL1Timestamp()

	go func() {
		err = service.applyTransactionToTip(tx3)
	}()
	event3 := <-txCh

	if event3.Txs[0].GetMeta().L1Timestamp != ts3 {
		t.Fatal("bad malleation")
	}
	// Ensure that the timestamp didn't change
	if ts3 != service.GetLatestL1Timestamp() {
		t.Fatal("timestamp updated when it shouldn't have")
	}
}

// Test that the L1 blocknumber is updated correctly
func TestSyncServiceL1BlockNumberUpdate(t *testing.T) {
	service, txCh, _, err := newTestSyncService(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Get the L1 blocknumber from the sync service
	// It should be initialized to 0
	bn := service.GetLatestL1BlockNumber()
	if bn != 0 {
		t.Fatalf("Unexpected timestamp: %d", bn)
	}

	tx1 := setMockTxL1BlockNumber(mockTx(), new(big.Int).SetUint64(1))
	go func() {
		err = service.applyTransactionToTip(tx1)
	}()
	event1 := <-txCh

	// Ensure that the L1 blocknumber was not
	// malleated
	if event1.Txs[0].L1BlockNumber().Uint64() != 1 {
		t.Fatal("wrong l1 blocknumber")
	}

	// Ensure that the latest L1 blocknumber was
	// updated
	if service.GetLatestL1BlockNumber() != 1 {
		t.Fatal("sync service latest l1 blocknumber not updated")
	}

	// Ensure that a tx without a L1 blocknumber gets one
	// assigned
	tx2 := setMockTxL1BlockNumber(mockTx(), nil)
	if tx2.L1BlockNumber() != nil {
		t.Fatal("non nil l1 blocknumber")
	}
	go func() {
		err = service.applyTransactionToTip(tx2)
	}()
	event2 := <-txCh

	if event2.Txs[0].L1BlockNumber() == nil {
		t.Fatal("tx not assigned an l1 blocknumber")
	}
	if event2.Txs[0].L1BlockNumber().Uint64() != service.GetLatestL1BlockNumber() {
		t.Fatal("tx assigned incorrect l1 blocknumber")
	}

	// Ensure that the latest L1 blocknumber doesn't go backwards
	latest := service.GetLatestL1BlockNumber()
	tx3 := setMockTxL1BlockNumber(mockTx(), new(big.Int).SetUint64(latest-1))
	go func() {
		err = service.applyTransactionToTip(tx3)
	}()
	event3 := <-txCh
	if service.GetLatestL1BlockNumber() != latest {
		t.Fatal("block number went backwards")
	}

	if event3.Txs[0].L1BlockNumber().Uint64() != latest-1 {
		t.Fatal("l1 block number was malleated")
	}
}

// Test that the `RollupTransaction` ends up in the transaction cache
// after the transaction enqueued event is emitted. Set `false` as
// the argument to start as a sequencer
func TestSyncServiceTransactionEnqueued(t *testing.T) {
	service, txCh, _, err := newTestSyncService(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	// The timestamp is in the rollup transaction
	timestamp := uint64(24)
	// The target is the `to` field on the transaction
	target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
	// The layer one transaction origin is in the txmeta on the transaction
	l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
	// The gasLimit is the `gasLimit` on the transaction
	gasLimit := uint64(66)
	// The data is the `data` on the transaction
	data := []byte{0x02, 0x92}
	// The L1 blocknumber for the transaction's evm context
	l1BlockNumber := big.NewInt(100)
	// The queue index of the L1 to L2 transaction
	queueIndex := uint64(0)
	// The index in the ctc
	index := uint64(0)

	tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
	txMeta := types.NewTransactionMeta(
		l1BlockNumber,
		timestamp,
		&l1TxOrigin,
		types.QueueOriginL1ToL2,
		&index,
		&queueIndex,
		nil,
	)
	tx.SetTransactionMeta(txMeta)

	setupMockClient(service, map[string]interface{}{
		"GetEnqueue": []*types.Transaction{
			tx,
		},
	})

	// Run an iteration of the eloop
	err = nil
	go func() {
		err = service.syncQueueToTip()
	}()
	// Wait for the tx to be confirmed into the chain and then
	// make sure it is the transactions that was set up with in the mockclient
	event := <-txCh
	if err != nil {
		t.Fatal("sequencing failed", err)
	}
	if len(event.Txs) != 1 {
		t.Fatal("Unexpected number of transactions")
	}
	confirmed := event.Txs[0]

	if !reflect.DeepEqual(tx, confirmed) {
		t.Fatal("different txs")
	}
}

func TestTransactionToTipNoIndex(t *testing.T) {
	service, txCh, _, err := newTestSyncService(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Get a reference to the current next index to compare with the index that
	// is set to the transaction that is ingested
	nextIndex := service.GetNextIndex()

	timestamp := uint64(24)
	target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
	l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
	gasLimit := uint64(66)
	data := []byte{0x02, 0x92}
	l1BlockNumber := big.NewInt(100)

	tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
	meta := types.NewTransactionMeta(
		l1BlockNumber,
		timestamp,
		&l1TxOrigin,
		types.QueueOriginL1ToL2,
		nil, // The index is `nil`, expect it to be set afterwards
		nil,
		nil,
	)
	tx.SetTransactionMeta(meta)

	go func() {
		err = service.applyTransactionToTip(tx)
	}()
	event := <-txCh
	if err != nil {
		t.Fatal("Cannot apply transaction to the tip")
	}
	confirmed := event.Txs[0]
	// The transaction was applied without an index so the chain gave it the
	// next index
	index := confirmed.GetMeta().Index
	if index == nil {
		t.Fatal("Did not set index after applying tx to tip")
	}
	if *index != *service.GetLatestIndex() {
		t.Fatal("Incorrect latest index")
	}
	if *index != nextIndex {
		t.Fatal("Incorrect index")
	}
}

func TestTransactionToTipTimestamps(t *testing.T) {
	service, txCh, _, err := newTestSyncService(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Create two mock transactions with `nil` indices. This will allow
	// assertions around the indices being updated correctly. Set the timestamp
	// to 1 and 2 and assert that the timestamps in the sync service are updated
	// correctly
	tx1 := setMockTxL1Timestamp(mockTx(), 1)
	tx2 := setMockTxL1Timestamp(mockTx(), 2)

	txs := []*types.Transaction{
		tx1,
		tx2,
	}

	for _, tx := range txs {
		nextIndex := service.GetNextIndex()

		go func() {
			err = service.applyTransactionToTip(tx)
		}()
		event := <-txCh
		if err != nil {
			t.Fatal(err)
		}

		conf := event.Txs[0]
		// The index should be set to the next
		if conf.GetMeta().Index == nil {
			t.Fatal("Index is nil")
		}
		// The index that the sync service is tracking should be updated
		if *conf.GetMeta().Index != *service.GetLatestIndex() {
			t.Fatal("index on the service was not updated")
		}
		// The indexes should be incrementing by 1
		if *conf.GetMeta().Index != nextIndex {
			t.Fatalf("Mismatched index: got %d, expect %d", *conf.GetMeta().Index, nextIndex)
		}
		// The tx timestamp should be setting the services timestamp
		if conf.L1Timestamp() != service.GetLatestL1Timestamp() {
			t.Fatal("Mismatched timestamp")
		}
	}

	// Ensure that the timestamp was updated correctly
	ts := service.GetLatestL1Timestamp()
	if ts != tx2.L1Timestamp() {
		t.Fatal("timestamp not updated correctly")
	}

	// Send a transaction with no timestamp and then let it be updated
	// by the sync service. This will prevent monotonicity errors as well.
	// as give timestamps to queue origin sequencer transactions
	// Ensure that the timestamp is set to `time.Now`
	// when it is not set.
	tx3 := setMockTxL1Timestamp(mockTx(), 0)
	now := time.Now()
	go func() {
		err = service.applyTransactionToTip(tx3)
	}()
	result := <-txCh
	service.chainHeadCh <- core.ChainHeadEvent{}

	if result.Txs[0].L1Timestamp() != uint64(now.Unix()) {
		t.Fatal("Timestamp not updated correctly")
	}

	if service.GetLatestL1Timestamp() != uint64(now.Unix()) {
		t.Fatal("latest timestamp not updated correctly")
	}
}

func TestApplyIndexedTransaction(t *testing.T) {
	service, txCh, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Create three transactions, two of which have a duplicate index.
	// The first two transactions can be ingested without a problem and the
	// third transaction has a duplicate index so it will not be ingested.
	// Expect an error for the third transaction and expect the SyncService
	// global index to be updated with the first two transactions
	tx0 := setMockTxIndex(mockTx(), 0)
	tx1 := setMockTxIndex(mockTx(), 1)
	tx1a := setMockTxIndex(mockTx(), 1)

	go func() {
		err = service.applyIndexedTransaction(tx0)
	}()
	<-txCh
	if err != nil {
		t.Fatal(err)
	}
	if *tx0.GetMeta().Index != *service.GetLatestIndex() {
		t.Fatal("Latest index mismatch")
	}

	go func() {
		err = service.applyIndexedTransaction(tx1)
	}()
	<-txCh
	if err != nil {
		t.Fatal(err)
	}
	if *tx1.GetMeta().Index != *service.GetLatestIndex() {
		t.Fatal("Latest index mismatch")
	}

	err = service.applyIndexedTransaction(tx1a)
	if err == nil {
		t.Fatal(err)
	}
}

func TestApplyBatchedTransaction(t *testing.T) {
	service, txCh, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	// Create a transactoin with the index of 0
	tx0 := setMockTxIndex(mockTx(), 0)

	// Ingest through applyBatchedTransaction which should set the latest
	// verified index to the index of the transaction
	go func() {
		err = service.applyBatchedTransaction(tx0)
	}()
	service.chainHeadCh <- core.ChainHeadEvent{}
	<-txCh

	// Catch race conditions with the database write
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		for {
			if service.GetLatestVerifiedIndex() != nil {
				wg.Done()
				return
			}
			time.Sleep(100 * time.Millisecond)
		}
	}()
	wg.Wait()

	// Assert that the verified index is the same as the transaction index
	if *tx0.GetMeta().Index != *service.GetLatestVerifiedIndex() {
		t.Fatal("Latest verified index mismatch")
	}
}

func TestIsAtTip(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	data := []struct {
		tip    *uint64
		get    indexGetter
		expect bool
		err    error
	}{
		{
			tip: newUint64(1),
			get: func() (*uint64, error) {
				return newUint64(1), nil
			},
			expect: true,
			err:    nil,
		},
		{
			tip: newUint64(0),
			get: func() (*uint64, error) {
				return newUint64(1), nil
			},
			expect: false,
			err:    nil,
		},
		{
			tip: newUint64(1),
			get: func() (*uint64, error) {
				return newUint64(0), nil
			},
			expect: false,
			err:    errShortRemoteTip,
		},
		{
			tip: nil,
			get: func() (*uint64, error) {
				return nil, nil
			},
			expect: true,
			err:    nil,
		},
		{
			tip: nil,
			get: func() (*uint64, error) {
				return nil, errElementNotFound
			},
			expect: true,
			err:    nil,
		},
		{
			tip: newUint64(0),
			get: func() (*uint64, error) {
				return nil, errElementNotFound
			},
			expect: false,
			err:    nil,
		},
	}

	for _, d := range data {
		isAtTip, err := service.isAtTip(d.tip, d.get)
		if isAtTip != d.expect {
			t.Fatal("expected does not match")
		}
		if !errors.Is(err, d.err) {
			t.Fatal("error no match")
		}
	}
}

func TestSyncQueue(t *testing.T) {
	service, txCh, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	setupMockClient(service, map[string]interface{}{
		"GetEnqueue": []*types.Transaction{
			setMockQueueIndex(mockTx(), 0),
			setMockQueueIndex(mockTx(), 1),
			setMockQueueIndex(mockTx(), 2),
			setMockQueueIndex(mockTx(), 3),
		},
	})

	var tip *uint64
	go func() {
		tip, err = service.syncQueue()
	}()

	for i := 0; i < 4; i++ {
		service.chainHeadCh <- core.ChainHeadEvent{}
		event := <-txCh
		tx := event.Txs[0]
		if *tx.GetMeta().QueueIndex != uint64(i) {
			t.Fatal("queue index mismatch")
		}
	}

	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		for {
			if tip != nil {
				wg.Done()
				return
			}
			time.Sleep(100 * time.Millisecond)
		}
	}()
	wg.Wait()
	if tip == nil {
		t.Fatal("tip is nil")
	}
	// There were a total of 4 transactions synced and the indexing starts at 0
	if *service.GetLatestIndex() != 3 {
		t.Fatalf("Latest index mismatch")
	}
	// All of the transactions are `enqueue()`s
	if *service.GetLatestEnqueueIndex() != 3 {
		t.Fatal("Latest queue index mismatch")
	}
	if *tip != 3 {
		t.Fatal("Tip mismatch")
	}
}

func TestSyncServiceL1GasPrice(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	setupMockClient(service, map[string]interface{}{})

	if err != nil {
		t.Fatal(err)
	}

	gasBefore, err := service.RollupGpo.SuggestL1GasPrice(context.Background())
	if err != nil {
		t.Fatal(err)
	}

	if gasBefore.Cmp(big.NewInt(0)) != 0 {
		t.Fatal("expected 0 gas price, got", gasBefore)
	}

	state, err := service.bc.State()
	if err != nil {
		t.Fatal("Cannot get state db")
	}
	l1GasPrice := big.NewInt(100000000000)
	state.SetState(rcfg.L2GasPriceOracleAddress, rcfg.L1GasPriceSlot, common.BigToHash(l1GasPrice))
	_, _ = state.Commit(false)

	// Update the gas price
	service.updateL1GasPrice(state)

	gasAfter, err := service.RollupGpo.SuggestL1GasPrice(context.Background())
	if err != nil {
		t.Fatal(err)
	}

	if gasAfter.Cmp(l1GasPrice) != 0 {
		t.Fatal("expected 100 gas price, got", gasAfter)
	}
}

func TestSyncServiceL2GasPrice(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	price, err := service.RollupGpo.SuggestL2GasPrice(context.Background())
	if err != nil {
		t.Fatal("Cannot fetch execution price")
	}

	if price.Cmp(common.Big0) != 0 {
		t.Fatal("Incorrect gas price")
	}

	state, err := service.bc.State()
	if err != nil {
		t.Fatal("Cannot get state db")
	}
	l2GasPrice := big.NewInt(100000000000)
	state.SetState(rcfg.L2GasPriceOracleAddress, rcfg.L2GasPriceSlot, common.BigToHash(l2GasPrice))
	_, _ = state.Commit(false)

	service.updateL2GasPrice(state)

	post, err := service.RollupGpo.SuggestL2GasPrice(context.Background())
	if err != nil {
		t.Fatal("Cannot fetch execution price")
	}

	if l2GasPrice.Cmp(post) != 0 {
		t.Fatal("Gas price not updated")
	}
}

func TestSyncServiceGasPriceOracleOwnerAddress(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}
	// newTestSyncService doesn't set the initial owner address
	// so it initializes to the zero value
	owner := service.GasPriceOracleOwnerAddress()
	if *owner != (common.Address{}) {
		t.Fatal("address not initialized to 0")
	}

	state, err := service.bc.State()
	if err != nil {
		t.Fatal("cannot get state db")
	}

	// Update the owner in the state to a non zero address
	updatedOwner := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
	state.SetState(rcfg.L2GasPriceOracleAddress, rcfg.L2GasPriceOracleOwnerSlot, updatedOwner.Hash())
	hash, _ := state.Commit(false)

	// Update the cache based on the latest state root
	if err := service.updateGasPriceOracleCache(&hash); err != nil {
		t.Fatal(err)
	}
	got := service.GasPriceOracleOwnerAddress()
	if *got != updatedOwner {
		t.Fatalf("mismatch:\ngot %s\nexpected %s", got.Hex(), updatedOwner.Hex())
	}
}

// Only the gas price oracle owner can send 0 gas price txs
// when fees are enforced
func TestFeeGasPriceOracleOwnerTransactions(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}
	signer := types.NewEIP155Signer(big.NewInt(420))

	// Fees must be enforced for this test
	service.enforceFees = true
	// Generate a key
	key, _ := crypto.GenerateKey()
	owner := crypto.PubkeyToAddress(key.PublicKey)
	// Set as the owner on the SyncService
	service.gasPriceOracleOwnerAddress = owner
	if owner != *service.GasPriceOracleOwnerAddress() {
		t.Fatal("owner mismatch")
	}
	// Create a mock transaction and sign using the
	// owner's key
	tx := mockTx()
	// Make sure the gas price is 0 on the dummy tx
	if tx.GasPrice().Cmp(common.Big0) != 0 {
		t.Fatal("gas price not 0")
	}
	// Sign the dummy tx with the owner key
	signedTx, err := types.SignTx(tx, signer, key)
	if err != nil {
		t.Fatal(err)
	}
	// Verify the fee of the signed tx, ensure it does not error
	if err := service.verifyFee(signedTx); err != nil {
		t.Fatal(err)
	}
	// Generate a new random key that is not the owner
	badKey, _ := crypto.GenerateKey()
	// Ensure that it is not the owner
	if owner == crypto.PubkeyToAddress(badKey.PublicKey) {
		t.Fatal("key mismatch")
	}
	// Sign the transaction with the bad key
	badSignedTx, err := types.SignTx(tx, signer, badKey)
	if err != nil {
		t.Fatal(err)
	}
	// Attempt to verify the fee of the bad tx
	// It should error and be a errZeroGasPriceTx
	if err := service.verifyFee(badSignedTx); err != nil {
		if !errors.Is(errZeroGasPriceTx, err) {
			t.Fatal(err)
		}
	} else {
		t.Fatal("err is nil")
	}
}

// Pass true to set as a verifier
func TestSyncServiceSync(t *testing.T) {
	service, txCh, sub, err := newTestSyncService(true, nil)
	defer sub.Unsubscribe()
	if err != nil {
		t.Fatal(err)
	}

	timestamp := uint64(24)
	target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
	l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
	gasLimit := uint64(66)
	data := []byte{0x02, 0x92}
	l1BlockNumber := big.NewInt(100)
	queueIndex := uint64(0)
	index := uint64(0)
	tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
	txMeta := types.NewTransactionMeta(
		l1BlockNumber,
		timestamp,
		&l1TxOrigin,
		types.QueueOriginL1ToL2,
		&index,
		&queueIndex,
		nil,
	)
	tx.SetTransactionMeta(txMeta)

	setupMockClient(service, map[string]interface{}{
		"GetTransaction": []*types.Transaction{
			tx,
		},
	})

	err = nil
	go func() {
		err = service.syncTransactionsToTip()
	}()
	event := <-txCh
	if err != nil {
		t.Fatal("verification failed", err)
	}

	if len(event.Txs) != 1 {
		t.Fatal("Unexpected number of transactions")
	}
	confirmed := event.Txs[0]

	if !reflect.DeepEqual(tx, confirmed) {
		t.Fatal("different txs")
	}
}

func TestInitializeL1ContextPostGenesis(t *testing.T) {
	service, _, _, err := newTestSyncService(true, nil)
	if err != nil {
		t.Fatal(err)
	}

	timestamp := uint64(24)
	target := common.HexToAddress("0x04668ec2f57cc15c381b461b9fedab5d451c8f7f")
	l1TxOrigin := common.HexToAddress("0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8")
	gasLimit := uint64(66)
	data := []byte{0x02, 0x92}
	l1BlockNumber := big.NewInt(100)
	queueIndex := uint64(100)
	index := uint64(120)
	tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
	txMeta := types.NewTransactionMeta(
		l1BlockNumber,
		timestamp,
		&l1TxOrigin,
		types.QueueOriginL1ToL2,
		&index,
		&queueIndex,
		nil,
	)
	tx.SetTransactionMeta(txMeta)

	setupMockClient(service, map[string]interface{}{
		"GetEnqueue": []*types.Transaction{
			tx,
		},
		"GetEthContext": []*EthContext{
			{
				BlockNumber: uint64(10),
				BlockHash:   common.Hash{},
				Timestamp:   timestamp,
			},
		},
	})

	header := types.Header{
		Number: big.NewInt(0),
		Time:   11,
	}

	number := uint64(10)
	tx.SetL1Timestamp(timestamp)
	tx.SetL1BlockNumber(number)
	block := types.NewBlock(&header, []*types.Transaction{tx}, []*types.Header{}, []*types.Receipt{})
	service.bc.SetCurrentBlock(block)

	err = service.initializeLatestL1(big.NewInt(0))
	if err != nil {
		t.Fatal(err)
	}

	latestL1Timestamp := service.GetLatestL1Timestamp()
	latestL1BlockNumber := service.GetLatestL1BlockNumber()
	if number != latestL1BlockNumber {
		t.Fatalf("number does not match, got %d, expected %d", latestL1BlockNumber, number)
	}
	if latestL1Timestamp != timestamp {
		t.Fatal("timestamp does not match")
	}
}

func TestBadFeeThresholds(t *testing.T) {
	// Create the deps for the sync service
	cfg, txPool, chain, db, err := newTestSyncServiceDeps(false, nil)
	if err != nil {
		t.Fatal(err)
	}

	tests := map[string]struct {
		thresholdUp   *big.Float
		thresholdDown *big.Float
		err           error
	}{
		"nil-values": {
			thresholdUp:   nil,
			thresholdDown: nil,
			err:           nil,
		},
		"good-values": {
			thresholdUp:   new(big.Float).SetFloat64(2),
			thresholdDown: new(big.Float).SetFloat64(0.8),
			err:           nil,
		},
		"bad-value-up": {
			thresholdUp:   new(big.Float).SetFloat64(0.8),
			thresholdDown: nil,
			err:           errBadConfig,
		},
		"bad-value-down": {
			thresholdUp:   nil,
			thresholdDown: new(big.Float).SetFloat64(1.1),
			err:           errBadConfig,
		},
	}

	for name, tt := range tests {
		t.Run(name, func(t *testing.T) {
			cfg.FeeThresholdDown = tt.thresholdDown
			cfg.FeeThresholdUp = tt.thresholdUp

			_, err := NewSyncService(context.Background(), cfg, txPool, chain, db)
			if !errors.Is(err, tt.err) {
				t.Fatalf("%s: %s", name, err)
			}
		})
	}
}

func newTestSyncServiceDeps(isVerifier bool, alloc *common.Address) (Config, *core.TxPool, *core.BlockChain, ethdb.Database, error) {
	chainCfg := params.AllEthashProtocolChanges
	chainID := big.NewInt(420)
	chainCfg.ChainID = chainID

	engine := ethash.NewFaker()
	db := rawdb.NewMemoryDatabase()
	genesis := new(core.Genesis)
	if alloc != nil {
		genesis.Alloc = make(core.GenesisAlloc)
		genesis.Alloc[*alloc] = core.GenesisAccount{
			Balance: new(big.Int).SetUint64(100000000000000),
		}
	}
	_ = genesis.MustCommit(db)
	chain, err := core.NewBlockChain(db, nil, chainCfg, engine, vm.Config{}, nil)
	if err != nil {
		return Config{}, nil, nil, nil, fmt.Errorf("Cannot initialize blockchain: %w", err)
	}
	chaincfg := params.ChainConfig{ChainID: chainID}

	txPool := core.NewTxPool(core.TxPoolConfig{PriceLimit: 0}, &chaincfg, chain)
	cfg := Config{
		CanonicalTransactionChainDeployHeight: big.NewInt(0),
		IsVerifier:                            isVerifier,
		// Set as an empty string as this is a dummy value anyways.
		// The client needs to be mocked with a mockClient
		RollupClientHttp: "",
		Backend:          BackendL2,
	}
	return cfg, txPool, chain, db, nil
}

func newTestSyncService(isVerifier bool, alloc *common.Address) (*SyncService, chan core.NewTxsEvent, event.Subscription, error) {
	cfg, txPool, chain, db, err := newTestSyncServiceDeps(isVerifier, alloc)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("Cannot initialize syncservice: %w", err)
	}
	service, err := NewSyncService(context.Background(), cfg, txPool, chain, db)
	if err != nil {
		return nil, nil, nil, fmt.Errorf("Cannot initialize syncservice: %w", err)
	}

	service.RollupGpo = gasprice.NewRollupOracle()
	txCh := make(chan core.NewTxsEvent, 1)
	sub := service.SubscribeNewTxsEvent(txCh)

	return service, txCh, sub, nil
}

type mockClient struct {
	getEnqueueCallCount            int
	getEnqueue                     []*types.Transaction
	getTransactionCallCount        int
	getTransaction                 []*types.Transaction
	getEthContextCallCount         int
	getEthContext                  []*EthContext
	getLatestEthContext            *EthContext
	getLatestEnqueueIndex          []func() (*uint64, error)
	getLatestEnqueueIndexCallCount int
}

func setupMockClient(service *SyncService, responses map[string]interface{}) {
	client := newMockClient(responses)
	service.client = client
	service.RollupGpo = gasprice.NewRollupOracle()
}

func newMockClient(responses map[string]interface{}) *mockClient {
	getEnqueueResponses := []*types.Transaction{}
	getTransactionResponses := []*types.Transaction{}
	getEthContextResponses := []*EthContext{}
	getLatestEthContextResponse := &EthContext{}
	getLatestEnqueueIndexResponses := []func() (*uint64, error){}

	enqueue, ok := responses["GetEnqueue"]
	if ok {
		getEnqueueResponses = enqueue.([]*types.Transaction)
	}
	getTx, ok := responses["GetTransaction"]
	if ok {
		getTransactionResponses = getTx.([]*types.Transaction)
	}
	getCtx, ok := responses["GetEthContext"]
	if ok {
		getEthContextResponses = getCtx.([]*EthContext)
	}
	getLatestCtx, ok := responses["GetLatestEthContext"]
	if ok {
		getLatestEthContextResponse = getLatestCtx.(*EthContext)
	}
	getLatestEnqueueIdx, ok := responses["GetLatestEnqueueIndex"]
	if ok {
		getLatestEnqueueIndexResponses = getLatestEnqueueIdx.([]func() (*uint64, error))
	}

	return &mockClient{
		getEnqueue:            getEnqueueResponses,
		getTransaction:        getTransactionResponses,
		getEthContext:         getEthContextResponses,
		getLatestEthContext:   getLatestEthContextResponse,
		getLatestEnqueueIndex: getLatestEnqueueIndexResponses,
	}
}

func (m *mockClient) GetEnqueue(index uint64) (*types.Transaction, error) {
	if m.getEnqueueCallCount < len(m.getEnqueue) {
		tx := m.getEnqueue[m.getEnqueueCallCount]
		m.getEnqueueCallCount++
		return tx, nil
	}
	return nil, errors.New("")
}

func (m *mockClient) GetLatestEnqueue() (*types.Transaction, error) {
	if len(m.getEnqueue) == 0 {
		return &types.Transaction{}, errors.New("enqueue not found")
	}
	return m.getEnqueue[len(m.getEnqueue)-1], nil
}

func (m *mockClient) GetTransaction(index uint64, backend Backend) (*types.Transaction, error) {
	if m.getTransactionCallCount < len(m.getTransaction) {
		tx := m.getTransaction[m.getTransactionCallCount]
		m.getTransactionCallCount++
		return tx, nil
	}
	return nil, fmt.Errorf("Cannot get transaction: mocks (%d), call count (%d)", len(m.getTransaction), m.getTransactionCallCount)
}

func (m *mockClient) GetLatestTransaction(backend Backend) (*types.Transaction, error) {
	if len(m.getTransaction) == 0 {
		return nil, errors.New("No transactions")
	}
	return m.getTransaction[len(m.getTransaction)-1], nil
}

func (m *mockClient) GetEthContext(index uint64) (*EthContext, error) {
	if m.getEthContextCallCount < len(m.getEthContext) {
		ctx := m.getEthContext[m.getEthContextCallCount]
		m.getEthContextCallCount++
		return ctx, nil
	}
	return nil, errors.New("Cannot get eth context")
}

func (m *mockClient) GetLatestEthContext() (*EthContext, error) {
	return m.getLatestEthContext, nil
}

func (m *mockClient) GetLastConfirmedEnqueue() (*types.Transaction, error) {
	return nil, errElementNotFound
}

func (m *mockClient) GetLatestTransactionBatch() (*Batch, []*types.Transaction, error) {
	return nil, nil, nil
}

func (m *mockClient) GetTransactionBatch(index uint64) (*Batch, []*types.Transaction, error) {
	return nil, nil, nil
}

func (m *mockClient) SyncStatus(backend Backend) (*SyncStatus, error) {
	return &SyncStatus{
		Syncing: false,
	}, nil
}

func (m *mockClient) GetLatestEnqueueIndex() (*uint64, error) {
	enqueue, err := m.GetLatestEnqueue()
	if err != nil {
		return nil, err
	}
	if enqueue == nil {
		return nil, errElementNotFound
	}
	return enqueue.GetMeta().QueueIndex, nil
}

func (m *mockClient) GetLatestTransactionBatchIndex() (*uint64, error) {
	return nil, nil
}

func (m *mockClient) GetLatestTransactionIndex(backend Backend) (*uint64, error) {
	tx, err := m.GetLatestTransaction(backend)
	if err != nil {
		return nil, err
	}
	return tx.GetMeta().Index, nil
}

func mockTx() *types.Transaction {
	address := make([]byte, 20)
	rand.Read(address)

	target := common.BytesToAddress(address)
	timestamp := uint64(0)

	rand.Read(address)
	l1TxOrigin := common.BytesToAddress(address)

	gasLimit := uint64(0)
	data := []byte{0x00, 0x00}
	l1BlockNumber := big.NewInt(0)

	tx := types.NewTransaction(0, target, big.NewInt(0), gasLimit, big.NewInt(0), data)
	meta := types.NewTransactionMeta(
		l1BlockNumber,
		timestamp,
		&l1TxOrigin,
		types.QueueOriginSequencer,
		nil,
		nil,
		nil,
	)
	tx.SetTransactionMeta(meta)
	return tx
}

func setMockTxL1Timestamp(tx *types.Transaction, ts uint64) *types.Transaction {
	meta := tx.GetMeta()
	meta.L1Timestamp = ts
	tx.SetTransactionMeta(meta)
	return tx
}

func setMockTxL1BlockNumber(tx *types.Transaction, bn *big.Int) *types.Transaction {
	meta := tx.GetMeta()
	meta.L1BlockNumber = bn
	tx.SetTransactionMeta(meta)
	return tx
}

func setMockTxIndex(tx *types.Transaction, index uint64) *types.Transaction {
	meta := tx.GetMeta()
	meta.Index = &index
	tx.SetTransactionMeta(meta)
	return tx
}

func setMockQueueIndex(tx *types.Transaction, index uint64) *types.Transaction {
	meta := tx.GetMeta()
	meta.QueueIndex = &index
	tx.SetTransactionMeta(meta)
	return tx
}

func setMockQueueOrigin(tx *types.Transaction, qo types.QueueOrigin) *types.Transaction {
	meta := tx.GetMeta()
	meta.QueueOrigin = qo
	tx.SetTransactionMeta(meta)
	return tx
}

func newUint64(n uint64) *uint64 {
	return &n
}