// Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package types

import (
	"bytes"
	"hash"
	"math/big"
	"reflect"
	"testing"

	"github.com/stretchr/testify/require"
	"golang.org/x/crypto/sha3"

	"github.com/autonity/autonity/common"
	"github.com/autonity/autonity/common/hexutil"
	"github.com/autonity/autonity/common/math"
	"github.com/autonity/autonity/crypto"
	"github.com/autonity/autonity/crypto/blst"
	"github.com/autonity/autonity/params"
	"github.com/autonity/autonity/rlp"
)

// from bcValidBlockTest.json, "SimpleTx"
func TestBlockEncoding(t *testing.T) {
	// this block now has baseFee = new(big.Int) since we do not allow baseFee = nil anymore
	blockEnc := common.FromHex("f90261f901faa083cafc574e1f51ba9dc0568fc617a08ea2429fb384059c972f13b19fa1c8dd55a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a05fe50b260da6308036625b850b5d6ced6d0a9f814c0688bc91ffb7b7a3a54b67a0bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd8825208845506eb0780a0bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff49888a13a5a8c8f2bb1c480f861f85f800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba09bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094fa08a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1c0")
	var block Block
	if err := rlp.DecodeBytes(blockEnc, &block); err != nil {
		t.Fatal("decode error: ", err)
	}

	check := func(f string, got, want interface{}) {
		if !reflect.DeepEqual(got, want) {
			t.Errorf("%s mismatch: got %v, want %v", f, got, want)
		}
	}
	check("Difficulty", block.Difficulty(), big.NewInt(131072))
	check("GasLimit", block.GasLimit(), uint64(3141592))
	check("GasUsed", block.GasUsed(), uint64(21000))
	check("Coinbase", block.Coinbase(), common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1"))
	check("MixDigest", block.MixDigest(), common.HexToHash("bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498"))
	check("Root", block.Root(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017"))
	check("Hash", block.Hash(), common.HexToHash("0xae9d971d16de73f69f940f1bd4ce5961158781176e73abea92a2b8781403885e"))
	check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4))
	check("Time", block.Time(), uint64(1426516743))
	check("Size", block.Size(), common.StorageSize(len(blockEnc)))

	tx1 := NewTransaction(0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(10), 50000, big.NewInt(10), nil)
	tx1, _ = tx1.WithSignature(HomesteadSigner{}, common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100"))
	check("len(Transactions)", len(block.Transactions()), 1)
	check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash())
	ourBlockEnc, err := rlp.EncodeToBytes(&block)
	if err != nil {
		t.Fatal("encode error: ", err)
	}
	if !bytes.Equal(ourBlockEnc, blockEnc) {
		t.Errorf("encoded block mismatch:\ngot:  %x\nwant: %x", ourBlockEnc, blockEnc)
	}
}

func TestHeaderEncodeDecodeJson(t *testing.T) {
	c := &Committee{
		Members: []CommitteeMember{{
			Address:           common.HexToAddress("0x76a685e4bf8cbcd25d7d3b6c342f64a30b503380"),
			ConsensusKeyBytes: hexutil.MustDecode("0x951f3f7ab473eb0d00eaaa569ba1a0be2877b794e29e0cbf504b7f00cb879a824b0b913397e0071a87cebaae2740002b"),
			VotingPower:       hexutil.MustDecodeBig("0x3039"),
		}, {
			Address:           common.HexToAddress("0xc44276975a6c2d12e62e18d814b507c38fc3646f"),
			ConsensusKeyBytes: hexutil.MustDecode("0x8bddc21fca7f3a920064729547605c73e55c17e20917eddc8788b97990c0d7e9420e51a97ea400fb58a5c28fa63984eb"),
			VotingPower:       hexutil.MustDecodeBig("0x3039"),
		}, {
			Address:           common.HexToAddress("0x1a72cb9d17c9e7acad03b4d3505f160e3782f2d5"),
			ConsensusKeyBytes: hexutil.MustDecode("0x9679c8ebd47d18b93acd90cd380debdcfdb140f38eca207c61463a47be85398ec3082a66f7f30635c11470f5c8e5cf6b"),
			VotingPower:       hexutil.MustDecodeBig("0x3039"),
		}, {
			Address:           common.HexToAddress("0xb2a0eea815fe9ba3cd9db5b230ec4db5286ad200"),
			ConsensusKeyBytes: hexutil.MustDecode("0xa22d806dc2aec2a8a644d83cbd6d2d6251936c2977910aa2f2f3b7c06a07234687f4a528c052c702984cf300f48b67fe"),
			VotingPower:       hexutil.MustDecodeBig("0x3039"),
		}, {
			Address:           common.HexToAddress("0xbaa58a01e5ca81dc288e2c46a8a467776bdb81c6"),
			ConsensusKeyBytes: hexutil.MustDecode("0xa460c204c407b6272f7731b0d15daca8f2564cf7ace301769e3b42de2482fc3bf8116dd13c0545e806441d074d02dcc2"),
			VotingPower:       hexutil.MustDecodeBig("0x3039"),
		}},
	}

	epoch := &Epoch{
		PreviousEpochBlock: common.Big1,
		NextEpochBlock:     common.Big256,
		Committee:          c,
		OmissionDelta:      common.Big5,
		Eip1559: &Eip1559Params{
			MinBaseFee:               new(big.Int).SetUint64(params.TestMinBaseFee),
			BaseFeeChangeDenominator: new(big.Int).SetUint64(8),
			ElasticityMultiplier:     common.Big2,
			GasLimitBoundDivisor:     new(big.Int).SetUint64(1024),
		},
	}

	t.Run("encode / decode with not nil epoch in block header", func(t *testing.T) {
		header := &Header{
			ParentHash:        common.HexToHash("0a5843ac1cb04865017cb35a57b50b07084e5fcee39b5acadade33149f4fff9e"),
			UncleHash:         common.HexToHash("0a5843ac1c124732472342342387423897431293123020912dade33149f4fffe"),
			Coinbase:          common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1"),
			Root:              common.HexToHash("0a5843ac1cb0486345235234564778768967856745645654649f4fff9321321e"),
			TxHash:            common.HexToHash("0a58213121cb0486345235234564778768967856745645654649f4fff932132e"),
			ReceiptHash:       common.HexToHash("9a58213121cb0486345235234564778768967856745645654649f4fff932132e"),
			Bloom:             BytesToBloom(bytes.Repeat([]byte("a"), 128)),
			Difficulty:        big.NewInt(199),
			Number:            big.NewInt(239),
			GasLimit:          uint64(1000),
			GasUsed:           uint64(400),
			Time:              uint64(12343),
			MixDigest:         common.HexToHash("0a58213121cb0486345235234564778768967853123645654649f4fff932132e"),
			Nonce:             [8]byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07},
			BaseFee:           big.NewInt(20000),
			Epoch:             epoch,
			ProposerSeal:      bytes.Repeat([]byte("c"), 65),
			Round:             uint64(3),
			QuorumCertificate: &AggregateSignature{},
		}

		err := header.Epoch.Committee.Enrich()
		require.NoError(t, err)

		// fill in some additional fields
		seal1, err := blst.SignatureFromBytes(hexutil.MustDecode("0xb0a87fe1d955b5526110f5eb2c9681e8ab5bddf77dd68a92480789b684f3b5e14586979bb64d84b6b885d12429ec92a6129598be4ba56bf2dccecfac0bead996a105c55f5b6c816384aa312cfc66dc648e8e7851eadfaa7091c2c472c732d021"))
		require.NoError(t, err)
		seal2, err := blst.SignatureFromBytes(hexutil.MustDecode("0xa2f685ab4925fa955796dc2fe83038036ec96a19ce7c8c76ab6ec2a65143a35a3540ee902fb87755ba8566f6550bc4ef1024489b34d2ad0ac1f3d2d238f265b5ebe2e1cd265472bb352bf3ecc57ec4269931c9dc8fcdf83fbe0bb1f9ec5cefd1"))
		require.NoError(t, err)

		header.QuorumCertificate.Signers = &Signers{Bitmap: NewBitmap(), Coefficients: make([]*big.Int, 0)}
		bm, fine := new(big.Int).SetString("4400", 16)
		require.True(t, fine)
		header.QuorumCertificate.Signers.Bitmap = (*Bitmap)(bm)
		sig := blst.AggregateSignatures([]blst.Signature{seal1, seal2})
		header.QuorumCertificate.Signature = sig.(*blst.BlsSignature)

		header.ActivityProof = header.QuorumCertificate.Copy()
		header.ActivityProofRound = 12

		hExtra := headerExtra{
			Epoch:              epoch,
			ProposerSeal:       header.ProposerSeal,
			Round:              header.Round,
			QuorumCertificate:  header.QuorumCertificate,
			ActivityProof:      header.ActivityProof,
			ActivityProofRound: header.ActivityProofRound,
		}

		extra, err := rlp.EncodeToBytes(hExtra)
		require.NoError(t, err)
		header.Extra = extra

		// encode to JSON
		json, err := header.MarshalJSON()
		require.NoError(t, err)

		// decode
		headerDecoded := new(Header)
		err = headerDecoded.UnmarshalJSON(json)
		require.NoError(t, err)

		// decoded struct should be equal to original struct
		equal := reflect.DeepEqual(header, headerDecoded)
		require.True(t, equal)

		// re-serialize decoded header, bytes should be equal
		json2, err := headerDecoded.MarshalJSON()
		require.NoError(t, err)
		require.True(t, bytes.Equal(json, json2))
	})

	t.Run("encode / decode with nil epoch in block header", func(t *testing.T) {
		header := &Header{
			ParentHash:        common.HexToHash("0a5843ac1cb04865017cb35a57b50b07084e5fcee39b5acadade33149f4fff9e"),
			UncleHash:         common.HexToHash("0a5843ac1c124732472342342387423897431293123020912dade33149f4fffe"),
			Coinbase:          common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1"),
			Root:              common.HexToHash("0a5843ac1cb0486345235234564778768967856745645654649f4fff9321321e"),
			TxHash:            common.HexToHash("0a58213121cb0486345235234564778768967856745645654649f4fff932132e"),
			ReceiptHash:       common.HexToHash("9a58213121cb0486345235234564778768967856745645654649f4fff932132e"),
			Bloom:             BytesToBloom(bytes.Repeat([]byte("a"), 128)),
			Difficulty:        big.NewInt(199),
			Number:            big.NewInt(239),
			GasLimit:          uint64(1000),
			GasUsed:           uint64(400),
			Time:              uint64(12343),
			MixDigest:         common.HexToHash("0a58213121cb0486345235234564778768967853123645654649f4fff932132e"),
			Nonce:             [8]byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07},
			BaseFee:           big.NewInt(20000),
			Epoch:             nil,
			ProposerSeal:      bytes.Repeat([]byte("c"), 65),
			Round:             uint64(3),
			QuorumCertificate: &AggregateSignature{},
		}

		// fill in some additional fields
		seal1, err := blst.SignatureFromBytes(hexutil.MustDecode("0xb0a87fe1d955b5526110f5eb2c9681e8ab5bddf77dd68a92480789b684f3b5e14586979bb64d84b6b885d12429ec92a6129598be4ba56bf2dccecfac0bead996a105c55f5b6c816384aa312cfc66dc648e8e7851eadfaa7091c2c472c732d021"))
		require.NoError(t, err)
		seal2, err := blst.SignatureFromBytes(hexutil.MustDecode("0xa2f685ab4925fa955796dc2fe83038036ec96a19ce7c8c76ab6ec2a65143a35a3540ee902fb87755ba8566f6550bc4ef1024489b34d2ad0ac1f3d2d238f265b5ebe2e1cd265472bb352bf3ecc57ec4269931c9dc8fcdf83fbe0bb1f9ec5cefd1"))
		require.NoError(t, err)

		header.QuorumCertificate.Signers = &Signers{Bitmap: NewBitmap(), Coefficients: make([]*big.Int, 0)}
		bm, fine := new(big.Int).SetString("4400", 16)
		require.True(t, fine)
		header.QuorumCertificate.Signers.Bitmap = (*Bitmap)(bm)
		sig := blst.AggregateSignatures([]blst.Signature{seal1, seal2})
		header.QuorumCertificate.Signature = sig.(*blst.BlsSignature)

		header.ActivityProof = header.QuorumCertificate.Copy()
		header.ActivityProofRound = 12

		hExtra := headerExtra{
			Epoch:              nil,
			ProposerSeal:       header.ProposerSeal,
			Round:              header.Round,
			QuorumCertificate:  header.QuorumCertificate,
			ActivityProof:      header.ActivityProof,
			ActivityProofRound: header.ActivityProofRound,
		}

		extra, err := rlp.EncodeToBytes(hExtra)
		require.NoError(t, err)
		header.Extra = extra

		// encode to JSON
		json, err := header.MarshalJSON()
		require.NoError(t, err)

		// decode
		headerDecoded := new(Header)
		err = headerDecoded.UnmarshalJSON(json)
		require.NoError(t, err)

		// decoded struct should be equal to original struct
		equal := reflect.DeepEqual(header, headerDecoded)
		require.True(t, equal)

		// re-serialize decoded header, bytes should be equal
		json2, err := headerDecoded.MarshalJSON()
		require.NoError(t, err)
		require.True(t, bytes.Equal(json, json2))
	})
}

func TestEIP1559BlockEncoding(t *testing.T) {
	blockEnc := common.FromHex("f9030bf901fea083cafc574e1f51ba9dc0568fc617a08ea2429fb384059c972f13b19fa1c8dd55a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a05fe50b260da6308036625b850b5d6ced6d0a9f814c0688bc91ffb7b7a3a54b67a0bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd8825208845506eb0780a0bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff49888a13a5a8c8f2bb1c4843b9aca00f90106f85f800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba09bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094fa08a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1b8a302f8a0018080843b9aca008301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8c0")
	var block Block
	if err := rlp.DecodeBytes(blockEnc, &block); err != nil {
		t.Fatal("decode error: ", err)
	}

	check := func(f string, got, want interface{}) {
		if !reflect.DeepEqual(got, want) {
			t.Errorf("%s mismatch: got %v, want %v", f, got, want)
		}
	}

	check("Difficulty", block.Difficulty(), big.NewInt(131072))
	check("GasLimit", block.GasLimit(), uint64(3141592))
	check("GasUsed", block.GasUsed(), uint64(21000))
	check("Coinbase", block.Coinbase(), common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1"))
	check("MixDigest", block.MixDigest(), common.HexToHash("bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498"))
	check("Root", block.Root(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017"))
	check("Hash", block.Hash(), common.HexToHash("c7252048cd273fe0dac09650027d07f0e3da4ee0675ebbb26627cea92729c372"))
	check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4))
	check("Time", block.Time(), uint64(1426516743))
	check("Size", block.Size(), common.StorageSize(len(blockEnc)))
	check("BaseFee", block.BaseFee(), new(big.Int).SetUint64(params.InitialBaseFee))

	tx1 := NewTransaction(0, common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"), big.NewInt(10), 50000, big.NewInt(10), nil)
	tx1, _ = tx1.WithSignature(HomesteadSigner{}, common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100"))

	addr := common.HexToAddress("0x0000000000000000000000000000000000000001")
	accesses := AccessList{AccessTuple{
		Address: addr,
		StorageKeys: []common.Hash{
			{0},
		},
	}}
	to := common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87")
	txdata := &DynamicFeeTx{
		ChainID:    big.NewInt(1),
		Nonce:      0,
		To:         &to,
		Gas:        123457,
		GasFeeCap:  new(big.Int).Set(block.BaseFee()),
		GasTipCap:  big.NewInt(0),
		AccessList: accesses,
		Data:       []byte{},
	}
	tx2 := NewTx(txdata)
	tx2, err := tx2.WithSignature(LatestSignerForChainID(big.NewInt(1)), common.Hex2Bytes("fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a800"))
	if err != nil {
		t.Fatal("invalid signature error: ", err)
	}

	check("len(Transactions)", len(block.Transactions()), 2)
	check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash())
	check("Transactions[1].Hash", block.Transactions()[1].Hash(), tx2.Hash())
	check("Transactions[1].Type", block.Transactions()[1].Type(), tx2.Type())
	ourBlockEnc, err := rlp.EncodeToBytes(&block)
	if err != nil {
		t.Fatal("encode error: ", err)
	}
	if !bytes.Equal(ourBlockEnc, blockEnc) {
		t.Errorf("encoded block mismatch:\ngot:  %x\nwant: %x", ourBlockEnc, blockEnc)
	}
}

func TestEIP2718BlockEncoding(t *testing.T) {
	// this block now has baseFee = new(big.Int) since we do not allow baseFee = nil anymore
	blockEnc := common.FromHex("f9031af90212a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a0e6e49996c7ec59f7a23d22b83239a60151512c65613bf84a0d7da336399ebc4aa0cafe75574d59780665a97fbfd11365c7545aa8f1abf4e5e12e8243334ef7286bb901000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083020000820200832fefd882a410845506eb0796636f6f6c65737420626c6f636b206f6e20636861696ea0bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff49888a13a5a8c8f2bb1c480f90101f85f800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba09bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094fa08a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b1b89e01f89b01800a8301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000001a03dbacc8d0259f2508625e97fdfc57cd85fdd16e5821bc2c10bdd1a52649e8335a0476e10695b183a87b0aa292a7f4b78ef0c3fbe62aa2c42c84e1d9c3da159ef14c0")
	var block Block
	if err := rlp.DecodeBytes(blockEnc, &block); err != nil {
		t.Fatal("decode error: ", err)
	}

	check := func(f string, got, want interface{}) {
		if !reflect.DeepEqual(got, want) {
			t.Errorf("%s mismatch: got %v, want %v", f, got, want)
		}
	}
	check("Difficulty", block.Difficulty(), big.NewInt(131072))
	check("GasLimit", block.GasLimit(), uint64(3141592))
	check("GasUsed", block.GasUsed(), uint64(42000))
	check("Coinbase", block.Coinbase(), common.HexToAddress("8888f1f195afa192cfee860698584c030f4c9db1"))
	check("MixDigest", block.MixDigest(), common.HexToHash("bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498"))
	check("Root", block.Root(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017"))
	check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4))
	check("Time", block.Time(), uint64(1426516743))
	check("Size", block.Size(), common.StorageSize(len(blockEnc)))

	// Create legacy tx.
	to := common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87")
	tx1 := NewTx(&LegacyTx{
		Nonce:    0,
		To:       &to,
		Value:    big.NewInt(10),
		Gas:      50000,
		GasPrice: big.NewInt(10),
	})
	sig := common.Hex2Bytes("9bea4c4daac7c7c52e093e6a4c35dbbcf8856f1af7b059ba20253e70848d094f8a8fae537ce25ed8cb5af9adac3f141af69bd515bd2ba031522df09b97dd72b100")
	tx1, _ = tx1.WithSignature(HomesteadSigner{}, sig)

	// Create ACL tx.
	addr := common.HexToAddress("0x0000000000000000000000000000000000000001")
	tx2 := NewTx(&AccessListTx{
		ChainID:    big.NewInt(1),
		Nonce:      0,
		To:         &to,
		Gas:        123457,
		GasPrice:   big.NewInt(10),
		AccessList: AccessList{{Address: addr, StorageKeys: []common.Hash{{0}}}},
	})
	sig2 := common.Hex2Bytes("3dbacc8d0259f2508625e97fdfc57cd85fdd16e5821bc2c10bdd1a52649e8335476e10695b183a87b0aa292a7f4b78ef0c3fbe62aa2c42c84e1d9c3da159ef1401")
	tx2, _ = tx2.WithSignature(NewEIP2930Signer(big.NewInt(1)), sig2)

	check("len(Transactions)", len(block.Transactions()), 2)
	check("Transactions[0].Hash", block.Transactions()[0].Hash(), tx1.Hash())
	check("Transactions[1].Hash", block.Transactions()[1].Hash(), tx2.Hash())
	check("Transactions[1].Type()", block.Transactions()[1].Type(), uint8(AccessListTxType))

	ourBlockEnc, err := rlp.EncodeToBytes(&block)
	if err != nil {
		t.Fatal("encode error: ", err)
	}
	if !bytes.Equal(ourBlockEnc, blockEnc) {
		t.Errorf("encoded block mismatch:\ngot:  %x\nwant: %x", ourBlockEnc, blockEnc)
	}
}

func TestUncleHash(t *testing.T) {
	uncles := make([]*Header, 0)
	h := CalcUncleHash(uncles)
	exp := common.HexToHash("1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347")
	if h != exp {
		t.Fatalf("empty uncle hash is wrong, got %x != %x", h, exp)
	}
}

func headerWithQuorumCertificate(quorumCertificate *AggregateSignature) *Header {
	return &Header{
		MixDigest:         BFTDigest,
		QuorumCertificate: quorumCertificate,
		// need to assign these fields because rlp decode will instantiate them
		// since they have no rlp:"nil" tag
		Difficulty:   new(big.Int),
		Number:       new(big.Int),
		BaseFee:      new(big.Int),
		ProposerSeal: make([]byte, 0),
	}
}

func TestQuorumCertificateDeserialization(t *testing.T) {
	// if nil when encoded, should be nil when decoded
	header := headerWithQuorumCertificate(nil)
	b, err := rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded := &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.Nil(t, headerDecoded.QuorumCertificate)
	require.Equal(t, header, headerDecoded)

	// if signature or signers is nil, decode should error out
	header = headerWithQuorumCertificate(&AggregateSignature{Signature: nil, Signers: nil})
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	sig, err := blst.SignatureFromBytes(hexutil.MustDecode("0xb0a87fe1d955b5526110f5eb2c9681e8ab5bddf77dd68a92480789b684f3b5e14586979bb64d84b6b885d12429ec92a6129598be4ba56bf2dccecfac0bead996a105c55f5b6c816384aa312cfc66dc648e8e7851eadfaa7091c2c472c732d021"))
	require.NoError(t, err)
	header = headerWithQuorumCertificate(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: nil})
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	header = headerWithQuorumCertificate(&AggregateSignature{Signature: nil, Signers: NewSigners(committee)})
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// empty signers is not allowed
	header = headerWithQuorumCertificate(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: &Signers{}})
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// signers that exceed quorum cap are not allowed
	header = headerWithQuorumCertificate(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: NewSigners(committee)})
	header.QuorumCertificate.Signers.Bitmap.Set(0)
	header.QuorumCertificate.Signers.Coefficients = []*big.Int{new(big.Int).SetUint64(1 << common.QuorumCap)}
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	validQuorumCertificate := &AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: NewSigners(committee)}
	validQuorumCertificate.Signers.increment(0)
	header = headerWithQuorumCertificate(validQuorumCertificate)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.NotNil(t, headerDecoded.QuorumCertificate)
	require.NotNil(t, headerDecoded.QuorumCertificate.Signature)
	require.NotNil(t, headerDecoded.QuorumCertificate.Signers)
	require.Equal(t, validQuorumCertificate.Signature.Marshal(), headerDecoded.QuorumCertificate.Signature.Marshal())
	require.Equal(t, validQuorumCertificate.Signers.Bitmap, headerDecoded.QuorumCertificate.Signers.Bitmap)
	require.Equal(t, validQuorumCertificate.Signers.Coefficients, headerDecoded.QuorumCertificate.Signers.Coefficients)

	err = headerDecoded.QuorumCertificate.Signers.Validate(committee)
	require.NoError(t, err)
	require.Equal(t, header, headerDecoded)
}

func headerWithActivityProof(activityProof *AggregateSignature, activityProofRound uint64) *Header {
	return &Header{
		MixDigest:          BFTDigest,
		ActivityProof:      activityProof,
		ActivityProofRound: activityProofRound,
		// need to assign these fields because rlp decode will instantiate them
		// since they have no rlp:"nil" tag
		Difficulty:   new(big.Int),
		Number:       new(big.Int),
		BaseFee:      new(big.Int),
		ProposerSeal: make([]byte, 0),
	}
}

func TestActivityProofDeserialization(t *testing.T) {
	// if nil when encoded, should be nil when decoded
	header := headerWithActivityProof(nil, 0)
	b, err := rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded := &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.Nil(t, headerDecoded.ActivityProof)
	require.Equal(t, header, headerDecoded)

	// if nil when encoded, having non zero activity proof round will make the decoding fail
	header = headerWithActivityProof(nil, 12)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// if signature or signers is nil, decode should error out
	header = headerWithActivityProof(&AggregateSignature{Signature: nil, Signers: nil}, 0)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	sig, err := blst.SignatureFromBytes(hexutil.MustDecode("0xb0a87fe1d955b5526110f5eb2c9681e8ab5bddf77dd68a92480789b684f3b5e14586979bb64d84b6b885d12429ec92a6129598be4ba56bf2dccecfac0bead996a105c55f5b6c816384aa312cfc66dc648e8e7851eadfaa7091c2c472c732d021"))
	require.NoError(t, err)
	header = headerWithActivityProof(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: nil}, 12)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	header = headerWithActivityProof(&AggregateSignature{Signature: nil, Signers: NewSigners(committee)}, 0)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// empty signers is not allowed
	header = headerWithActivityProof(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: &Signers{}}, 4)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// signers that exceed quorum cap are not allowed
	header = headerWithActivityProof(&AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: NewSigners(committee)}, 4)
	header.ActivityProof.Signers.Bitmap.Set(0)
	header.ActivityProof.Signers.Coefficients = []*big.Int{new(big.Int).SetUint64(1 << common.QuorumCap)}
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	validActivityProof := &AggregateSignature{Signature: sig.(*blst.BlsSignature), Signers: NewSigners(committee)}
	validActivityProof.Signers.increment(0)
	header = headerWithActivityProof(validActivityProof, 4)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.NotNil(t, headerDecoded.ActivityProof)
	require.NotNil(t, headerDecoded.ActivityProof.Signature)
	require.NotNil(t, headerDecoded.ActivityProof.Signers)
	require.Equal(t, validActivityProof.Signature.Marshal(), headerDecoded.ActivityProof.Signature.Marshal())
	require.Equal(t, validActivityProof.Signers.Bitmap, headerDecoded.ActivityProof.Signers.Bitmap)
	require.Equal(t, validActivityProof.Signers.Coefficients, headerDecoded.ActivityProof.Signers.Coefficients)
	require.Equal(t, uint64(4), headerDecoded.ActivityProofRound)

	err = headerDecoded.ActivityProof.Signers.Validate(committee)
	require.NoError(t, err)
	require.Equal(t, header.ActivityProof.Signers, headerDecoded.ActivityProof.Signers)
	require.Equal(t, header, headerDecoded)
}

func headerWithEpoch(epoch *Epoch) *Header {
	return &Header{
		MixDigest: BFTDigest,
		Epoch:     epoch,
		// need to assign these fields because rlp decode will instantiate them
		// since they have no rlp:"nil" tag
		Difficulty:   new(big.Int),
		Number:       new(big.Int),
		BaseFee:      new(big.Int),
		ProposerSeal: make([]byte, 0),
	}
}

func TestEpochDeserialization(t *testing.T) {
	// if nil when encoded, should be nil when decoded
	header := headerWithEpoch(nil)
	b, err := rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded := &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.Nil(t, headerDecoded.Epoch)
	require.Equal(t, header, headerDecoded)

	// valid epoch information
	validEpoch := &Epoch{
		Committee:          committee.Copy(),
		PreviousEpochBlock: common.Big0,
		NextEpochBlock:     common.Big256,
		OmissionDelta:      common.Big5,
		Eip1559: &Eip1559Params{
			MinBaseFee:               new(big.Int).SetUint64(params.TestMinBaseFee),
			BaseFeeChangeDenominator: new(big.Int).SetUint64(8),
			ElasticityMultiplier:     new(big.Int).SetUint64(2),
			GasLimitBoundDivisor:     new(big.Int).SetUint64(1024),
		},
	}
	require.NoError(t, validEpoch.Committee.Enrich())
	header = headerWithEpoch(validEpoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.NoError(t, err)
	require.Equal(t, header, headerDecoded)
	require.True(t, validEpoch.Equal(headerDecoded.Epoch))

	// committee should not be nil
	epoch := validEpoch.Copy()
	epoch.Committee = nil
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// committee should have at least 1 member
	epoch = validEpoch.Copy()
	epoch.Committee = &Committee{}
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// committee should have valid keys
	epoch = validEpoch.Copy()
	epoch.Committee.Members[1].ConsensusKeyBytes = make([]byte, 27)
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// delta should not be 0
	epoch = validEpoch.Copy()
	epoch.OmissionDelta = common.Big0
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// base fee change denominator should not be 0
	epoch = validEpoch.Copy()
	epoch.Eip1559.BaseFeeChangeDenominator = common.Big0
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// elasticity multiplier should not be 0
	epoch = validEpoch.Copy()
	epoch.Eip1559.ElasticityMultiplier = common.Big0
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)

	// gasLimitBoundDivisor should not be 0
	epoch = validEpoch.Copy()
	epoch.Eip1559.GasLimitBoundDivisor = common.Big0
	header = headerWithEpoch(epoch)
	b, err = rlp.EncodeToBytes(header)
	require.NoError(t, err)
	headerDecoded = &Header{}
	err = rlp.Decode(bytes.NewReader(b), headerDecoded)
	require.Error(t, err)
	t.Log(err)
	require.Equal(t, &Header{}, headerDecoded)
}

var benchBuffer = bytes.NewBuffer(make([]byte, 0, 32000))

func BenchmarkEncodeBlock(b *testing.B) {
	block := makeBenchBlock()
	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		benchBuffer.Reset()
		if err := rlp.Encode(benchBuffer, block); err != nil {
			b.Fatal(err)
		}
	}
}

// testHasher is the helper tool for transaction/receipt list hashing.
// The original hasher is trie, in order to get rid of import cycle,
// use the testing hasher instead.
type testHasher struct {
	hasher hash.Hash
}

func newHasher() *testHasher {
	return &testHasher{hasher: sha3.NewLegacyKeccak256()}
}

func (h *testHasher) Reset() {
	h.hasher.Reset()
}

func (h *testHasher) Update(key, val []byte) {
	h.hasher.Write(key)
	h.hasher.Write(val)
}

func (h *testHasher) Hash() common.Hash {
	return common.BytesToHash(h.hasher.Sum(nil))
}

func makeBenchBlock() *Block {
	var (
		key, _   = crypto.GenerateKey()
		txs      = make([]*Transaction, 70)
		receipts = make([]*Receipt, len(txs))
		signer   = LatestSigner(params.TestChainConfig)
		uncles   = make([]*Header, 3)
	)
	header := &Header{
		Difficulty: math.BigPow(11, 11),
		Number:     math.BigPow(2, 9),
		GasLimit:   12345678,
		GasUsed:    1476322,
		Time:       9876543,
		Extra:      []byte("coolest block on chain"),
	}
	for i := range txs {
		amount := math.BigPow(2, int64(i))
		price := big.NewInt(300000)
		data := make([]byte, 100)
		tx := NewTransaction(uint64(i), common.Address{}, amount, 123457, price, data)
		signedTx, err := SignTx(tx, signer, key)
		if err != nil {
			panic(err)
		}
		txs[i] = signedTx
		receipts[i] = NewReceipt(make([]byte, 32), false, tx.Gas())
	}
	for i := range uncles {
		uncles[i] = &Header{
			Difficulty: math.BigPow(11, 11),
			Number:     math.BigPow(2, 9),
			GasLimit:   12345678,
			GasUsed:    1476322,
			Time:       9876543,
			Extra:      []byte("benchmark uncle"),
		}
	}
	return NewBlock(header, txs, uncles, receipts, newHasher())
}

func TestRlpDecodeParentHash(t *testing.T) {
	// A minimum one
	want := common.HexToHash("0x112233445566778899001122334455667788990011223344556677889900aabb")
	if rlpData, err := rlp.EncodeToBytes(&Header{ParentHash: want}); err != nil {
		t.Fatal(err)
	} else {
		if have := HeaderParentHashFromRLP(rlpData); have != want {
			t.Fatalf("have %x, want %x", have, want)
		}
	}
	// And a maximum one
	// | Difficulty  | dynamic| *big.Int       | 0x5ad3c2c71bbff854908 (current mainnet TD: 76 bits) |
	// | Number      | dynamic| *big.Int       | 64 bits               |
	// | Extra       | dynamic| []byte         | 65+32 byte (clique)   |
	// | BaseFee     | dynamic| *big.Int       | 64 bits               |
	mainnetTd := new(big.Int)
	mainnetTd.SetString("5ad3c2c71bbff854908", 16)
	if rlpData, err := rlp.EncodeToBytes(&Header{
		ParentHash: want,
		Difficulty: mainnetTd,
		Number:     new(big.Int).SetUint64(math.MaxUint64),
		Extra:      make([]byte, 65+32),
		BaseFee:    new(big.Int).SetUint64(math.MaxUint64),
	}); err != nil {
		t.Fatal(err)
	} else {
		if have := HeaderParentHashFromRLP(rlpData); have != want {
			t.Fatalf("have %x, want %x", have, want)
		}
	}
	// Also test a very very large header.
	{
		// The rlp-encoding of the heder belowCauses _total_ length of 65540,
		// which is the first to blow the fast-path.
		h := Header{
			ParentHash: want,
			Extra:      make([]byte, 65041),
		}
		if rlpData, err := rlp.EncodeToBytes(&h); err != nil {
			t.Fatal(err)
		} else {
			if have := HeaderParentHashFromRLP(rlpData); have != want {
				t.Fatalf("have %x, want %x", have, want)
			}
		}
	}
	{
		// Test some invalid erroneous stuff
		for i, rlpData := range [][]byte{
			nil,
			common.FromHex("0x"),
			common.FromHex("0x01"),
			common.FromHex("0x3031323334"),
		} {
			if have, want := HeaderParentHashFromRLP(rlpData), (common.Hash{}); have != want {
				t.Fatalf("invalid %d: have %x, want %x", i, have, want)
			}
		}
	}
}

func TestAggregateSignatureWithSingleSigner(t *testing.T) {
	// test that having an aggregate signature (e.g. quorum certificate) signed by a single validator doesn't cause
	// any issues

	localCommittee, blsKeys := generateCommittee([]int{100, 1, 1, 1, 1}) // committee[0] has quorum
	t.Logf("committee[0] %s", localCommittee.Members[0].Address.String())

	msg := common.BytesToHash([]byte{0xca, 0xfe})
	signature := blsKeys[0].Sign(msg.Bytes())
	signers := NewSigners(localCommittee)
	signers.increment(0)

	aggregateSignature := NewAggregateSignature(signature.(*blst.BlsSignature), signers)
	require.False(t, aggregateSignature.Malformed())

	sigSigners, power, err := aggregateSignature.Validate(msg, localCommittee, true)
	t.Logf("signers %v, power: %v, err %v", sigSigners, power, err)
	require.NoError(t, err)

}
